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:Examples.java

/**
 * This example shows how to chain events from one Transformer
 * to another transformer, using the Transformer as a
 * SAX2 XMLFilter/XMLReader.// w w  w.  j a  va 2s  . 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 the simplest possible transformation from system id to output stream.
 *//*from w w  w.j  a  v a  2s. c om*/
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/*ww w .  j a  va 2 s . c  om*/
 * @param xmlFileContent1, first XML file content 
 * @param xmlFileContent2, second XML file content
 * @param xmlStyleSheet, XSL style sheet as a inputstream 
 * @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 String mergeTwoXMLFiles(String xmlFileContent1, final String xmlFileContent2,
        InputStream xmlStyleSheet, final String refCodeName) throws Exception, FileNotFoundException {

    Templates mergeXML2IntoStylesheet;
    TransformerFactory tFactory = TransformerFactory.newInstance();
    //StreamSource stylesheetStream = new StreamSource(new FileReader(xmlStyleSheet));
    StreamSource stylesheetStream = new StreamSource(xmlStyleSheet);

    mergeXML2IntoStylesheet = tFactory.newTemplates(stylesheetStream);
    StreamSource xml1Source = new StreamSource(new StringReader(xmlFileContent1));
    StringWriter mergedWriter = new StringWriter();
    StreamResult mergedResult = new StreamResult(mergedWriter);
    // Transformer is not guaranteed to be thread-safe -- therefore, we
    // need one per thread.
    Transformer mergingTransformer = mergeXML2IntoStylesheet.newTransformer();
    mergingTransformer.setURIResolver(new URIResolver() {
        public Source resolve(String href, String base) {
            if (href == null) {
                return null;
            } else if (href.equals(refCodeName)) {
                return (new StreamSource(new StringReader(xmlFileContent2)));
            } else {
                return null;
            }
        }
    });

    mergingTransformer.transform(xml1Source, mergedResult);
    return mergedWriter.toString();
}

From source file:nz.co.senanque.madura.spring.XSLSpringFactoryBean.java

/**
 * Load the XSLT document. The documentName can be a local resource file name
 * or a url pointing to a resource./*from w  ww .  java2 s.  c  o m*/
 * @param documentName
 * @return a Templates object containing the document
 * @throws DocumentException
 */
private Templates loadXSLT(InputStream in) {
    try {
        Source xsltSource = new StreamSource(in);
        TransformerFactory transFact = TransformerFactory.newInstance();
        Templates templates = transFact.newTemplates(xsltSource);
        return templates;
    } catch (Exception e) {
        throw new RuntimeException("failed to parse: " + getResource().getDescription(), e);
    }
}

From source file:Compile.java

/**
 * Compiles an XSL stylesheet into a translet, wraps the translet
 * inside a Templates object and dumps it to a file.
 */// w  w  w. j a  v  a2s. c o m
public void run(String xsl) {
    try {
        // Set XSLTC's TransformerFactory implementation as the default
        System.setProperty("javax.xml.transform.TransformerFactory",
                "org.apache.xalan.xsltc.trax.TransformerFactoryImpl");

        // Get an input stream for the XSL stylesheet
        StreamSource stylesheet = new StreamSource(xsl);

        // The TransformerFactory will compile the stylesheet and
        // put the translet classes inside the Templates object
        TransformerFactory factory = TransformerFactory.newInstance();
        factory.setAttribute("generate-translet", Boolean.TRUE);
        Templates templates = factory.newTemplates(stylesheet);
    } catch (Exception e) {
        System.err.println("Exception: " + e);
        e.printStackTrace();
    }
    System.exit(0);
}

From source file:edu.duke.cabig.c3pr.rules.common.adapter.CaAERSJBossXSLTRuleAdapter.java

public Package adapt(RuleSet ruleSet) throws RuleException {

    /*/*from  ww  w. j a va 2  s .co m*/
     * Add adverseEventEvaluationResult here and remove it from everywhere else since this is a
     * hidden column, it should not be used for authoring. It is used only at runtime. So it
     * make sense to add to the condition here. IMP: This is only required for caAERS project.
     */
    List<Rule> rules = ruleSet.getRule();
    for (Rule r : rules) {
        Column column_fixed = new Column();
        column_fixed.setObjectType("edu.duke.cabig.c3pr.rules.common.AdverseEventEvaluationResult");
        column_fixed.setIdentifier("adverseEventEvaluationResult");
        r.getCondition().getColumn().add(column_fixed);

    }

    List<String> imports = ruleSet.getImport();
    if (log.isDebugEnabled()) {
        log.debug("Size of imports:" + imports.size());
        for (String s : imports) {
            log.debug("each import :" + s);
        }
    }

    // marshal and transform
    String xml1 = XMLUtil.marshal(ruleSet);
    log.debug("Marshalled, Before transforming using [jboss-rules-intermediate.xsl]:\r\n" + xml1);

    XsltTransformer xsltTransformer = new XsltTransformer();
    String xml = "";

    try {
        xml = xsltTransformer.toXml(xml1, "jboss-rules-intermediate.xsl");
        log.debug("After transforming using [jboss-rules-intermediate.xsl] :\n\r" + xml);
    } catch (Exception e) {
        log.error("Exception while transforming to New Scheme: " + e.getMessage(), e);
    }

    StringWriter writer = new StringWriter();

    System.setProperty("javax.xml.transform.TransformerFactory",
            "org.apache.xalan.processor.TransformerFactoryImpl");
    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    try {

        Templates translet = transformerFactory.newTemplates(new StreamSource(
                Thread.currentThread().getContextClassLoader().getResourceAsStream("new_jobss_rules.xsl")));
        Transformer transformer = translet.newTransformer();

        if (log.isDebugEnabled()) {
            log.debug("Before transforming using [new_jobss_rules.xsl] :\r\n" + xml);
            StringWriter strWriter = new StringWriter();
            transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(strWriter));
            log.debug("After transforming using [new_jboss_rules.xsl]:\r\n" + strWriter.toString());
        }

        transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(writer));

    } catch (Exception e) {
        log.error("Error while transforming using new_jboss_rules.xsl", e);
        throw new RuleException("Unable to transform using new_jboss_rules.xsl", e);
    }

    // create the rules package
    return XMLUtil.unmarshalToPackage(writer.toString());
}

From source file:com.esri.geoportal.commons.csw.client.impl.Profile.java

@Override
public String generateCSWGetRecordsRequest(ICriteria criteria) {
    String internalRequestXml = createInternalXmlRequest(criteria);
    try (ByteArrayInputStream internalRequestInputStream = new ByteArrayInputStream(
            internalRequestXml.getBytes("UTF-8"));
            InputStream reqXsltInputStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(Constants.CONFIG_FOLDER_PATH + "/" + getGetRecordsReqXslt())) {

        // create internal request DOM
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document internalRequestDOM = builder.parse(new InputSource(internalRequestInputStream));

        // create transformer
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Templates template = transformerFactory.newTemplates(new StreamSource(reqXsltInputStream));
        Transformer transformer = template.newTransformer();

        // perform transformation
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(internalRequestDOM), new StreamResult(writer));

        return writer.toString();
    } catch (Exception ex) {
        LOG.warn("Error creating CSW get records request.", ex);
        return "";
    }//from   w  w w. j ava  2s.com
}

From source file:net.sf.taverna.t2.activities.soaplab.views.SoaplabActivityContextualView.java

private String getMetadata() {
    try {/*from  ww  w .j a v a 2 s .c o m*/
        Configuration configuration = getConfigBean();
        JsonNode json = configuration.getJson();
        String endpoint = json.get("endpoint").textValue();
        Call call = (Call) new Service().createCall();
        call.setTimeout(new Integer(0));
        call.setTargetEndpointAddress(endpoint);
        call.setOperationName(new QName("describe"));
        String metadata = (String) call.invoke(new Object[0]);
        logger.info(metadata);
        // Old impl, returns a tree of the XML
        // ColXMLTree tree = new ColXMLTree(metadata);
        URL sheetURL = SoaplabActivityContextualView.class.getResource("/analysis_metadata_2_html.xsl");
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        logger.info(sheetURL.toString());
        Templates stylesheet = transformerFactory.newTemplates(new StreamSource(sheetURL.openStream()));
        Transformer transformer = stylesheet.newTransformer();
        StreamSource inputStream = new StreamSource(new ByteArrayInputStream(metadata.getBytes()));
        ByteArrayOutputStream transformedStream = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(transformedStream);
        transformer.transform(inputStream, result);
        transformedStream.flush();
        transformedStream.close();
        // String summaryText = "<html><head>"
        // + WorkflowSummaryAsHTML.STYLE_NOBG + "</head>"
        // + transformedStream.toString() + "</html>";
        // JEditorPane metadataPane = new ColJEditorPane("text/html",
        // summaryText);
        // metadataPane.setText(transformedStream.toString());
        // // logger.info(transformedStream.toString());
        // JScrollPane jsp = new JScrollPane(metadataPane,
        // JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        // JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        // jsp.setPreferredSize(new Dimension(0, 0));
        // jsp.getVerticalScrollBar().setValue(0);
        return transformedStream.toString();
    } catch (Exception ex) {
        return "<font color=\"red\">Error</font><p>An exception occured while trying to fetch Soaplab metadata from the server. The error was :<pre>"
                + ex.getMessage() + "</pre>";

    }
}

From source file:com.pactera.edg.am.metamanager.extractor.util.ExtractorContext.java

/**
 * ????XSLT/*w w  w . ja  v  a 2 s. co  m*/
 * 
 * @return the xsltTemplate throws Exception ?XLST
 */
public Templates getXsltTemplate(String xslt) throws IOException, TransformerConfigurationException {
    // if (!this.templates.containsKey(xslt)) {
    InputStream in = new DefaultResourceLoader().getResource(xslt).getInputStream();
    Source xsltSource = new SAXSource(new InputSource(in));
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setAttribute(FeatureKeys.DTD_VALIDATION, Boolean.FALSE); //TODO DTD?
    factory.setAttribute(FeatureKeys.SCHEMA_VALIDATION, 4);
    Templates xsltTemplate = factory.newTemplates(xsltSource);
    // this.templates.put(xslt, xsltTemplate);
    if (in != null)
        in.close();
    // }
    return xsltTemplate;
}

From source file:org.ambraproject.service.XMLServiceImpl.java

/**
 * Get a translet, compiled stylesheet, for the xslTemplate. If the doc is null
 * use the default template. If the doc is not null then get the DTD version.
 * IF the DTD version does not exist use the default template else use the
 * template associated with that version.
 *
 * @param  doc  the dtd version of document
 * @return Translet for the xslTemplate.
 * @throws javax.xml.transform.TransformerException TransformerException.
 *//*from   w  w  w . j  av a2 s .  co m*/
private Transformer getTranslet(Document doc) throws TransformerException, URISyntaxException {
    Transformer transformer;
    // key is "" if the Attribute does not exist
    String key = (doc == null) ? "default" : doc.getDocumentElement().getAttribute("dtd-version").trim();

    if ((!xslTemplateMap.containsKey(key)) || (key.equalsIgnoreCase(""))) {
        transformer = this.translet.newTransformer();
    } else {
        Templates translet;
        String templateName = xslTemplateMap.get(key);

        File file = getAsFile(templateName);
        if (!file.exists()) {
            file = new File(templateName);
        }
        // set the Templates
        final TransformerFactory tFactory = TransformerFactory.newInstance();
        translet = tFactory.newTemplates(new StreamSource(file));
        transformer = translet.newTransformer();
    }
    transformer.setParameter("pubAppContext", configuration.getString("ambra.platform.appContext", ""));
    return transformer;
}