Example usage for javax.xml.transform.sax TemplatesHandler getTemplates

List of usage examples for javax.xml.transform.sax TemplatesHandler getTemplates

Introduction

In this page you can find the example usage for javax.xml.transform.sax TemplatesHandler getTemplates.

Prototype

public Templates getTemplates();

Source Link

Document

When a TemplatesHandler object is used as a ContentHandler for the parsing of transformation instructions, it creates a Templates object, which the caller can get once the SAX events have been completed.

Usage

From source file:SAX2SAX.java

public static void main(String[] args)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {

    // Instantiate a TransformerFactory.
    TransformerFactory tFactory = TransformerFactory.newInstance();
    // Determine whether the TransformerFactory supports The use of SAXSource 
    // and SAXResult
    if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) {
        // Cast the TransformerFactory.
        SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory);
        // Create a ContentHandler to handle parsing of the stylesheet.
        TemplatesHandler templatesHandler = saxTFactory.newTemplatesHandler();

        // Create an XMLReader and set its ContentHandler.
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(templatesHandler);

        // Parse the stylesheet.                       
        reader.parse("birds.xsl");

        //Get the Templates object from the ContentHandler.
        Templates templates = templatesHandler.getTemplates();
        // Create a ContentHandler to handle parsing of the XML source.  
        TransformerHandler handler = saxTFactory.newTransformerHandler(templates);
        // Reset the XMLReader's ContentHandler.
        reader.setContentHandler(handler);

        // Set the ContentHandler to also function as a LexicalHandler, which
        // includes "lexical" events (e.g., comments and CDATA). 
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        FileOutputStream fos = new FileOutputStream("birds.out");

        java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml");
        xmlProps.setProperty("indent", "yes");
        xmlProps.setProperty("standalone", "no");
        Serializer serializer = SerializerFactory.getSerializer(xmlProps);
        serializer.setOutputStream(fos);

        // Set the result handling to be a serialization to the file output stream.
        Result result = new SAXResult(serializer.asContentHandler());
        handler.setResult(result);/*from   w  ww.  j  a va  2s .  co  m*/

        // Parse the XML input document.
        reader.parse("birds.xml");

        System.out.println("************* The result is in birds.out *************");
    } else
        System.out.println("The TransformerFactory does not support SAX input and SAX output");
}

From source file:Main.java

private static void transformInternal(final URIResolver xslResolver, final StreamSource xml,
        final InputSource xsl, final Map<String, Object> parameters, final StreamResult result)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerException {//from www  .  j ava 2s .  c o m
    final TransformerFactory tfactory = TransformerFactory.newInstance();
    tfactory.setURIResolver(xslResolver);

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // if so, we can safely cast
        final SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // create a Templates ContentHandler to handle parsing of the
        // stylesheet
        final javax.xml.transform.sax.TemplatesHandler templatesHandler = stfactory.newTemplatesHandler();
        templatesHandler.setDocumentLocator(emptyDocumentLocator);

        final XMLFilter filter = new XMLFilterImpl();
        filter.setParent(makeXMLReader());
        filter.setContentHandler(templatesHandler);

        // parse the stylesheet
        templatesHandler.setSystemId(xsl.getSystemId());
        filter.parse(xsl);

        // set xslt parameters
        final Transformer autobot = templatesHandler.getTemplates().newTransformer();
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                final String name = keys.next();
                final Object value = parameters.get(name);
                autobot.setParameter(name, value);
            }
        }

        // set saxon parameters
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                String name = keys.next();
                if (name.startsWith("saxon-")) {
                    final String value = parameters.get(name).toString();
                    name = name.replaceFirst("saxon\\-", "");
                    autobot.setOutputProperty(name, value);
                }
            }
        }

        // do the transform
        // logger.debug("SAX resolving systemIDs relative to: " +
        // templatesHandler.getSystemId());
        autobot.transform(xml, result);

    } else {
        throw new IllegalStateException("Factory doesn't implement SAXTransformerFactory");
    }
}

From source file:org.apache.cocoon.components.xslt.TraxProcessor.java

public TransformerHandlerAndValidity getTransformerHandlerAndValidity(Source stylesheet, XMLFilter filter)
        throws XSLTProcessorException {

    final String id = stylesheet.getURI();
    TransformerHandlerAndValidity handlerAndValidity;

    try {/*from w ww.  jav a2s  .co m*/
        handlerAndValidity = getTemplates(stylesheet, id);
        if (handlerAndValidity != null) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Reusing Templates for " + id);
            }
            return handlerAndValidity;
        }
    } catch (Exception e) {
        throw new XSLTProcessorException("Error retrieving template", e);
    }

    TraxErrorListener errorListener = new TraxErrorListener(getLogger(), stylesheet.getURI());
    try {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Creating new Templates for " + id);
        }

        m_factory.setErrorListener(errorListener);

        // Create a Templates ContentHandler to handle parsing of the
        // stylesheet.
        TemplatesHandler templatesHandler = m_factory.newTemplatesHandler();

        // Set the system ID for the template handler since some
        // TrAX implementations (XSLTC) rely on this in order to obtain
        // a meaningful identifier for the Templates instances.
        templatesHandler.setSystemId(id);
        if (filter != null) {
            filter.setContentHandler(templatesHandler);
        }

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Source = " + stylesheet + ", templatesHandler = " + templatesHandler);
        }

        // Initialize List for included validities
        SourceValidity validity = stylesheet.getValidity();
        if (validity != null && m_checkIncludes) {
            m_includesMap.put(id, new ArrayList());
        }

        try {
            // Process the stylesheet.
            sourceToSAX(stylesheet,
                    filter != null ? (ContentHandler) filter : (ContentHandler) templatesHandler);

            // Get the Templates object (generated during the parsing of
            // the stylesheet) from the TemplatesHandler.
            final Templates template = templatesHandler.getTemplates();

            if (null == template) {
                throw new XSLTProcessorException(
                        "Unable to create templates for stylesheet: " + stylesheet.getURI());
            }

            putTemplates(template, stylesheet, id);

            // Create transformer handler
            final TransformerHandler handler = m_factory.newTransformerHandler(template);
            handler.getTransformer().setErrorListener(new TraxErrorListener(getLogger(), stylesheet.getURI()));
            handler.getTransformer().setURIResolver(this);

            // Create aggregated validity
            AggregatedValidity aggregated = null;
            if (validity != null && m_checkIncludes) {
                List includes = (List) m_includesMap.get(id);
                if (includes != null) {
                    aggregated = new AggregatedValidity();
                    aggregated.add(validity);
                    for (int i = includes.size() - 1; i >= 0; i--) {
                        aggregated.add((SourceValidity) ((Object[]) includes.get(i))[1]);
                    }
                    validity = aggregated;
                }
            }

            // Create result
            handlerAndValidity = new MyTransformerHandlerAndValidity(handler, validity);
        } finally {
            if (m_checkIncludes)
                m_includesMap.remove(id);
        }

        return handlerAndValidity;
    } catch (Exception e) {
        Throwable realEx = errorListener.getThrowable();
        if (realEx == null)
            realEx = e;

        if (realEx instanceof RuntimeException) {
            throw (RuntimeException) realEx;
        }

        if (realEx instanceof XSLTProcessorException) {
            throw (XSLTProcessorException) realEx;
        }

        throw new XSLTProcessorException("Exception when creating Transformer from " + stylesheet.getURI(),
                realEx);
    }
}

From source file:org.toobsframework.transformpipeline.domain.BaseXMLTransformer.java

protected Templates getTemplates(String xsl, XMLReader reader)
        throws TransformerConfigurationException, TransformerException, IOException, SAXException {
    Templates templates = null;/*from   ww  w.  ja v a  2  s.  co  m*/
    if (templateCache.containsKey(xsl) && !doReload) {
        templates = templateCache.get(xsl);
    } else {

        // Get an XMLReader.
        if (reader == null) {
            reader = XMLReaderManager.getInstance().getXMLReader();
        }
        TemplatesHandler templatesHandler = saxTFactory.newTemplatesHandler();
        reader.setContentHandler(templatesHandler);

        try {
            reader.parse(getInputSource(xsl));
        } catch (MalformedURLException e) {
            log.info("Xerces Version: " + Version.getVersion());
            throw e;
        }
        templates = templatesHandler.getTemplates();

        templateCache.put(xsl, templates);
    }

    return templates;
}