Example usage for javax.xml.transform TransformerFactory newTemplates

List of usage examples for javax.xml.transform TransformerFactory newTemplates

Introduction

In this page you can find the example usage for javax.xml.transform TransformerFactory newTemplates.

Prototype

public abstract Templates newTemplates(Source source) throws TransformerConfigurationException;

Source Link

Document

Process the Source into a Templates object, which is a a compiled representation of the source.

Usage

From source file:org.dd4t.core.util.XSLTransformer.java

private Transformer getTransformer(String resource) throws TransformerConfigurationException {
    Transformer trans = null;/*from ww  w  . j a v  a2  s. c  o m*/
    Templates temp = null;

    // first, lets get the template
    if (CACHE.containsKey(resource)) {
        temp = CACHE.get(resource);
    } else {

        InputStream stream = null;
        try {
            stream = getClass().getResourceAsStream(resource);
            if (null == stream) {
                throw new TransformerConfigurationException(
                        "Resource '" + resource + "' could not be loaded. ");
            }
            StreamSource source = new StreamSource(stream);

            // instantiate a transformer
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            temp = transformerFactory.newTemplates(source);

            CACHE.put(resource, temp);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    trans = temp.newTransformer();
    return trans;
}

From source file:org.dhatim.templating.xslt.XslTemplateProcessor.java

@Override
protected void loadTemplate(SmooksResourceConfiguration resourceConfig)
        throws IOException, TransformerConfigurationException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    StreamSource xslStreamSource;
    boolean isInlineXSL = resourceConfig.isInline();
    byte[] xslBytes = resourceConfig.getBytes();

    xslString = new String(xslBytes, getEncoding().name());

    // If it's not a full XSL template, we need to make it so by wrapping it...
    isTemplatelet = isTemplatelet(isInlineXSL, new String(xslBytes));
    if (isTemplatelet) {
        String templateletWrapper = new String(
                StreamUtils.readStream(ClassUtil.getResourceAsStream("doc-files/templatelet.xsl", getClass())));
        String templatelet = new String(xslBytes);

        templateletWrapper = StringUtils.replace(templateletWrapper, "@@@templatelet@@@", templatelet);
        xslBytes = templateletWrapper.getBytes();
        xslString = new String(xslBytes, getEncoding().name());
    }/*from  w w  w.j  a v  a 2  s . c  o  m*/

    boolean failOnWarning = resourceConfig.getBoolParameter("failOnWarning", true);

    xslStreamSource = new StreamSource(new StringReader(xslString));
    transformerFactory.setErrorListener(new XslErrorListener(failOnWarning));
    xslTemplate = transformerFactory.newTemplates(xslStreamSource);
}

From source file:org.easyrec.util.core.Web.java

/**
 * This function returns a processed HTML Page from a given XML
 * transformed with an XSL.//from  w w  w.  j a  v a2s .c  om
 *
 * @param xmlUrl String
 * @param xslUrl String
 * @return String
 * @throws Exception Exception
 */
@SuppressWarnings({ "UnusedDeclaration" })
public static String transformXML(String xmlUrl, String xslUrl) throws Exception {

    String sHTML;

    try {

        TransformerFactory factory = TransformerFactory.newInstance();

        Templates sourceTemplate = factory.newTemplates(new StreamSource(xslUrl));

        Transformer sourceTransformer = sourceTemplate.newTransformer();

        URI uri = new URI("http", xmlUrl.replace("http:", ""), null);

        Source source = new StreamSource(uri.toURL().toString());

        StringWriter writer = new StringWriter();
        Result localResult = new StreamResult(writer);

        sourceTransformer.transform(source, localResult);
        sHTML = writer.toString();

    } catch (Exception e) {
        logger.warn("An error occurred!", e);
        throw new Exception();
    }
    return sHTML;
}

From source file:org.easyrec.utils.Web.java

/**
 * This function returns a processed HTML Page from a given XML
 * transformed with an XSL.//from w ww  .  j  a v  a 2s . co m
 *
 * @param xmlUrl String
 * @param xslUrl String
 * @return String
 * @throws Exception Exception
 */
@SuppressWarnings({ "UnusedDeclaration" })
public static String transformXML(String xmlUrl, String xslUrl) throws Exception {

    String sHTML;

    try {

        TransformerFactory factory = TransformerFactory.newInstance();

        Templates sourceTemplate = factory.newTemplates(new StreamSource(xslUrl));

        Transformer sourceTransformer = sourceTemplate.newTransformer();

        URI uri = new URI("http", xmlUrl.replace("http:", ""), null);

        Source source = new StreamSource(uri.toURL().toString());

        StringWriter writer = new StringWriter();
        Result localResult = new StreamResult(writer);

        sourceTransformer.transform(source, localResult);
        sHTML = writer.toString();

    } catch (Exception e) {
        throw new Exception();
    }
    return sHTML;
}

From source file:org.fcrepo.utilities.XmlTransformUtility.java

/**
 * Try to cache parsed Templates, but check for changes on disk
 * @param src//from ww w.  ja  v a  2  s.  c om
 * @return
 */
public static Templates getTemplates(File src) throws TransformerException {
    String key = src.getAbsolutePath();
    TimestampedCacheEntry<Templates> entry = TEMPLATES_CACHE.get(key);
    // check to see if it is null or has changed
    if (entry == null || entry.timestamp() < src.lastModified()) {
        TransformerFactory factory = null;
        try {
            factory = borrowTransformerFactory();
            Templates template = factory.newTemplates(new StreamSource(src));
            entry = new TimestampedCacheEntry<Templates>(src.lastModified(), template);
        } catch (Exception e) {
            throw new TransformerException(e.getMessage(), e);
        } finally {
            if (factory != null)
                returnTransformerFactory(factory);
        }
        TEMPLATES_CACHE.put(key, entry);
    }
    return entry.value();
}

From source file:org.fcrepo.utilities.XmlTransformUtility.java

public static Templates getTemplates(StreamSource source) throws TransformerException {
    TransformerFactory tf = null;
    Templates result = null;/*from   www  .ja v  a  2s . co m*/
    try {
        tf = borrowTransformerFactory();
        result = tf.newTemplates(source);
    } catch (Exception e) {
        throw new TransformerException(e.getMessage(), e);
    } finally {
        if (tf != null)
            returnTransformerFactory(tf);
    }
    return result;
}

From source file:org.geoserver.wfs.xslt.rest.XSLTDataFormat.java

@Override
protected Object read(InputStream in) throws IOException {
    // store in a string so that we can perform validation
    String xslt = IOUtils.toString(in);

    try {/* w w  w. j av a 2 s . c o  m*/
        Source xslSource = new StreamSource(new StringReader(xslt));
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.newTemplates(xslSource);
    } catch (Exception e) {
        throw new RestletException("Invalid XSLT : " + e.getMessage(), Status.CLIENT_ERROR_BAD_REQUEST);
    }

    return xslt;
}

From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java

/**
 * Creates a new <code>Templates</code> instance based on
 * the specified stylesheet.//from  w  ww .  j a v a2  s .  c  o  m
 *
 * @param xslSource - the source object that holds an XSL stylesheet URI,
 *                     input stream, etc.
 * @return Templates
 * @throws TransformerConfigurationException
 */
private Templates newTemplates(Source xslSource) throws TransformerConfigurationException {
    // Set the TransformerFactory system property to utilise translets
    // For more flexibility, load properties from a properties file
    // This will do the job for the time being
    logger.debug("Current TransformerFactory =[" + System.getProperty(TX_FACTORY_KEY) + "].");

    logger.debug("Setting a new TransformerFactory [" + TX_FACTORY_VALUE + "].");
    Properties props = System.getProperties();
    props.put(TX_FACTORY_KEY, TX_FACTORY_VALUE);
    System.setProperties(props);
    logger.debug("New TransformerFactory =[" + System.getProperty(TX_FACTORY_KEY) + "].");

    // Get a new TransformerFactory instance
    TransformerFactory tFactory = this.newTransformerFactory();

    // Create a new translet as a Templates object
    return tFactory.newTemplates(xslSource);
}

From source file:org.jzkit.search.util.RecordConversion.XSLFragmentTransformer.java

private void reloadStylesheet() throws javax.xml.transform.TransformerConfigurationException {
    log.debug("XSLFragmentTransformer::reloadStylesheet()");
    try {/*from ww w . j a v a2s. c o  m*/
        TransformerFactory tFactory = TransformerFactory.newInstance();
        if (ctx == null)
            throw new RuntimeException("Application Context Is Null. Cannot resolve resources");

        org.springframework.core.io.Resource r = ctx.getResource(the_path);
        if ((r != null) && (r.exists())) {
            URL path_url = r.getURL();
            URLConnection conn = path_url.openConnection();
            datestamp = conn.getDate();
            log.debug("get template for " + the_path + " url:" + path_url + " datestamp=" + datestamp);
            t = tFactory.newTemplates(new javax.xml.transform.stream.StreamSource(conn.getInputStream()));
        } else {
            log.error("Unable to resolve URL for " + the_path);
        }
    } catch (java.io.IOException ioe) {
        log.warn("Problem with XSL mapping", ioe);
        throw new RuntimeException("Unable to locate mapping: " + the_path);
    } catch (javax.xml.transform.TransformerConfigurationException tce) {
        log.warn("Problem with XSL mapping", tce);
        throw (tce);
    }

}

From source file:org.mule.tools.schemadocs.SchemaDocsMain.java

protected void processSchema(InputStream xslSource, OutputStream out)
        throws TransformerException, IOException, ParserConfigurationException {
    TransformerFactory factory = TransformerFactory.newInstance();
    Templates template = factory.newTemplates(new StreamSource(xslSource));
    Transformer xformer = template.newTransformer();
    Iterator urls = listSchema2().iterator();
    while (urls.hasNext()) {
        URL url = (URL) urls.next();
        String tag = tagFromFileName(url.getFile());
        logger.info(tag + " : " + url);
        xformer.setParameter(TAG, tag);//from  www . ja v  a  2 s  .  c om
        Source source = new StreamSource(url.openStream());
        xformer.transform(source, new StreamResult(out));
        //            xformer.transform(source, new StreamResult(System.out));
        out.flush();
    }
}