Example usage for javax.xml.transform Templates newTransformer

List of usage examples for javax.xml.transform Templates newTransformer

Introduction

In this page you can find the example usage for javax.xml.transform Templates newTransformer.

Prototype

Transformer newTransformer() throws TransformerConfigurationException;

Source Link

Document

Create a new transformation context for this Templates object.

Usage

From source file:JAXPTransletMultipleTransformations.java

static void doTransform(Templates translet, String xmlInURI, String htmlOutURI)
        throws TransformerException, FileNotFoundException {
    // For each transformation, instantiate a new Transformer, and perform
    // the transformation from a StreamSource to a StreamResult;
    Transformer transformer = translet.newTransformer();
    transformer.transform(new StreamSource(xmlInURI), new StreamResult(new FileOutputStream(htmlOutURI)));
}

From source file:ddf.util.XSLTUtil.java

/**
 * Performs an xsl transformation against an XML document
 *
 * @param template//ww w. jav  a 2 s.  c  o m
 *            The compiled XSL template to be run
 * @param xmlDoc
 *            xml document to be transformed
 * @param xslProperties
 *            default classification
 * @return the transformed document.
 * @throws TransformerException
 */
public static Document transform(Templates template, Document xmlDoc, Map<String, Object> parameters)
        throws TransformerException {
    ByteArrayOutputStream baos;
    ByteArrayInputStream bais = null;
    Document resultDoc;
    try {
        Transformer transformer = template.newTransformer();

        DBF.setNamespaceAware(true);
        DocumentBuilder builder = DBF.newDocumentBuilder();
        StreamResult resultOutput = null;
        Source source = new DOMSource(xmlDoc);
        baos = new ByteArrayOutputStream();
        try {
            resultOutput = new StreamResult(baos);
            if (parameters != null && !parameters.isEmpty()) {
                for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                    LOGGER.debug("Adding parameter key: {} value: {}", entry.getKey(), entry.getValue());
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (key != null && !key.isEmpty() && value != null) {
                        transformer.setParameter(key, value);
                    } else {
                        LOGGER.debug("Null or empty value for parameter: {}", entry.getKey());

                    }
                }
            } else {
                LOGGER.warn("All properties were null.  Using \"last-resort\" defaults: U, USA, MTS");
            }

            transformer.transform(source, resultOutput);
            bais = new ByteArrayInputStream(baos.toByteArray());
            resultDoc = builder.parse(bais);
        } finally {
            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(baos);
        }

        return resultDoc;
    } catch (TransformerException e) {
        LOGGER.warn(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        LOGGER.warn(e.getMessage(), e);
        throw new TransformerException("Error while transforming document: " + e.getMessage(), e);
    }
}

From source file:edu.harvard.hul.ois.fits.Fits.java

public static void outputStandardSchemaXml(FitsOutput fitsOutput, OutputStream out)
        throws XMLStreamException, IOException {
    XmlContent xml = fitsOutput.getStandardXmlContent();

    //create an xml output factory
    Transformer transformer = null;

    //initialize transformer for pretty print xslt
    TransformerFactory tFactory = TransformerFactory.newInstance();
    String prettyPrintXslt = FITS_XML + "prettyprint.xslt";
    try {/*from w w  w  . ja v  a 2  s.c  o m*/
        Templates template = tFactory.newTemplates(new StreamSource(prettyPrintXslt));
        transformer = template.newTransformer();
    } catch (Exception e) {
        transformer = null;
    }

    if (xml != null && transformer != null) {

        xml.setRoot(true);
        ByteArrayOutputStream xmlOutStream = new ByteArrayOutputStream();
        OutputStream xsltOutStream = new ByteArrayOutputStream();

        try {
            //send standard xml to the output stream
            XMLStreamWriter sw = xmlOutputFactory.createXMLStreamWriter(xmlOutStream);
            xml.output(sw);

            //convert output stream to byte array and read back in as inputstream
            Source source = new StreamSource(new ByteArrayInputStream(xmlOutStream.toByteArray()));
            Result rstream = new StreamResult(xsltOutStream);

            //apply the xslt
            transformer.transform(source, rstream);

            //send to the providedOutpuStream
            out.write(xsltOutStream.toString().getBytes("UTF-8"));
            out.flush();

        } catch (Exception e) {
            System.err.println("error converting output to a standard schema format");
        } finally {
            xmlOutStream.close();
            xsltOutStream.close();
        }

    } else {
        System.err.println("Error: output cannot be converted to a standard schema format for this file");
    }
}

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor//from  w  w w .  java  2 s  .c  o  m
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:XmlUtils.java

private static Transformer getTransformer(String xsltFile, boolean inClassPath)
        throws TransformerConfigurationException, IOException {
    Templates tpl = XmlUtils.templates.get(xsltFile);
    if (tpl == null) {
        InputStream stream;/*from   www . j  a va 2  s.co  m*/
        if (inClassPath)
            stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsltFile);
        else
            stream = new FileInputStream(xsltFile);
        Source xsltSource = new StreamSource(stream);
        tpl = XmlUtils.transFact.newTemplates(xsltSource);
        XmlUtils.templates.put(xsltFile, tpl);
    }
    return tpl.newTransformer();

}

From source file:Examples.java

/**
 * This shows how to set a parameter for use by the templates. Use 
 * two transformers to show that different parameters may be set 
 * on different transformers./*  ww  w  . jav a  2 s  .c  om*/
 */
public static void exampleParam(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Templates templates = tfactory.newTemplates(new StreamSource(xslID));
    Transformer transformer1 = templates.newTransformer();
    Transformer transformer2 = templates.newTransformer();

    transformer1.setParameter("a-param", "hello to you!");
    transformer1.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));

    System.out.println("\n=========");

    transformer2.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer2.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:Examples.java

/**
 * This example shows how to chain events from one Transformer
 * to another transformer, using the Transformer as a
 * SAX2 XMLFilter/XMLReader.//from  w  w  w  . ja va 2  s  .c o m
 */
public static void exampleXMLFilterChain(String sourceID, String xslID_1, String xslID_2, String xslID_3)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    Templates stylesheet1 = tfactory.newTemplates(new StreamSource(xslID_1));
    Transformer transformer1 = stylesheet1.newTransformer();

    // If one success, assume all will succeed.
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();

        XMLFilter filter1 = stf.newXMLFilter(new StreamSource(xslID_1));
        XMLFilter filter2 = stf.newXMLFilter(new StreamSource(xslID_2));
        XMLFilter filter3 = stf.newXMLFilter(new StreamSource(xslID_3));

        if (null != filter1) // If one success, assume all were success.
        {
            // transformer1 will use a SAX parser as it's reader.    
            filter1.setParent(reader);

            // transformer2 will use transformer1 as it's reader.
            filter2.setParent(filter1);

            // transform3 will use transform2 as it's reader.
            filter3.setParent(filter2);

            filter3.setContentHandler(new ExampleContentHandler());
            // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler());

            // Now, when you call transformer3 to parse, it will set  
            // itself as the ContentHandler for transform2, and 
            // call transform2.parse, which will set itself as the 
            // content handler for transform1, and call transform1.parse, 
            // which will set itself as the content listener for the 
            // SAX parser, and call parser.parse(new InputSource("xml/foo.xml")).
            filter3.parse(new InputSource(sourceID));
        } else {
            System.out.println("Can't do exampleXMLFilter because " + "tfactory doesn't support asXMLFilter()");
        }
    } else {
        System.out.println("Can't do exampleXMLFilter because " + "tfactory is not a SAXTransformerFactory");
    }
}

From source file:Examples.java

/**
 * Show how to override output properties.
 *//*from w  ww.  j  av  a  2  s  .com*/
public static void exampleOutputProperties(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException {

    TransformerFactory tfactory = TransformerFactory.newInstance();
    Templates templates = tfactory.newTemplates(new StreamSource(xslID));
    Properties oprops = templates.getOutputProperties();

    oprops.put(OutputKeys.INDENT, "yes");

    Transformer transformer = templates.newTransformer();

    transformer.setOutputProperties(oprops);
    transformer.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:Examples.java

/**
 * Show the simplest possible transformation from system id to output stream.
 *///from  ww  w  . ja  v a2 s.c o  m
public static void exampleUseTemplatesObj(String sourceID1, String sourceID2, String xslID)
        throws TransformerException, TransformerConfigurationException {

    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Create a templates object, which is the processed, 
    // thread-safe representation of the stylesheet.
    Templates templates = tfactory.newTemplates(new StreamSource(xslID));

    // Illustrate the fact that you can make multiple transformers 
    // from the same template.
    Transformer transformer1 = templates.newTransformer();
    Transformer transformer2 = templates.newTransformer();

    System.out.println("\n\n----- transform of " + sourceID1 + " -----");

    transformer1.transform(new StreamSource(sourceID1), new StreamResult(new OutputStreamWriter(System.out)));

    System.out.println("\n\n----- transform of " + sourceID2 + " -----");

    transformer2.transform(new StreamSource(sourceID2), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Merge two XML files using XSLT/*from   www .  j  a v  a2  s . co  m*/
 * @param xmlFileContent1, first XML file content 
 * @param xmlFileContent2, second XML file content
 * @param mergingStylesheet, the XSLT style sheet merging xml2 into xml1.
 * @param refCodeName, code name used in xsl sheet to refer xmlFile2 (example: semaine.mary.intonation ) 
 * @return output of merged xml file
 * @throws Exception
 * @throws FileNotFoundException
 */
public static Document mergeTwoXMLFiles(Document xmlFileContent1, final Document xmlFileContent2,
        Templates mergingStylesheet, final String refCodeName) throws Exception, FileNotFoundException {

    DOMSource xml1Source = new DOMSource(xmlFileContent1);
    DOMResult mergedDR = new DOMResult();
    // Transformer is not guaranteed to be thread-safe -- therefore, we
    // need one per thread.
    Transformer mergingTransformer = mergingStylesheet.newTransformer();
    mergingTransformer.setURIResolver(new URIResolver() {
        public Source resolve(String href, String base) {
            if (href == null) {
                return null;
            } else if (href.equals(refCodeName)) {
                return (new DOMSource(xmlFileContent2));
            } else {
                return null;
            }
        }
    });

    mergingTransformer.transform(xml1Source, mergedDR);
    return (Document) mergedDR.getNode();
}