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.ambraproject.service.XMLServiceImpl.java

/**
 * Initialization method called by Spring.
 *
 * @throws org.ambraproject.ApplicationException On Template creation Exceptions.
 *///from  w  w w.  jav a 2s  .  c  o m
public void init() throws ApplicationException {
    // set JAXP properties
    System.getProperties().putAll(xmlFactoryProperty);

    // Create a document builder factory and set the defaults
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    // set the Templates
    final TransformerFactory tFactory = TransformerFactory.newInstance();

    try {
        translet = tFactory.newTemplates(new StreamSource(xslDefaultTemplate));
    } catch (TransformerConfigurationException tce) {
        throw new ApplicationException(tce);
    }
}

From source file:fedora.server.rest.BaseRestResource.java

protected void transform(String xml, String xslt, Writer out)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
    File xslFile = new File(fedoraServer.getHomeDir(), xslt);
    TransformerFactory factory = TransformerFactory.newInstance();
    if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) {
        factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE);
    }/*from   w  w  w  .j a v  a 2 s  .co  m*/
    Templates template = factory.newTemplates(new StreamSource(xslFile));
    Transformer transformer = template.newTransformer();
    String appContext = getContext().getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME);
    transformer.setParameter("fedora", appContext);
    transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(out));
}

From source file:org.kuali.mobility.knowledgebase.service.KnowledgeBaseServiceImpl.java

private Templates getXslTemplates(String templatesCode) throws Exception {
    Xsl xsl = xslDao.findXslByCode(templatesCode);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Templates templates = transformerFactory
            .newTemplates(new StreamSource(new ByteArrayInputStream(xsl.getValue().getBytes())));
    //      Templates templates = transformerFactory.newTemplates(new StreamSource(new ByteArrayInputStream("test".getBytes())));
    return templates;
}

From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPQuery.java

/**
 * Generates an XML or HTML document based on a given stylesheet
 * @param xmlDoc Specifies the xml document
 * @param styleIn specifies the stylesheet
 * @return/*  w  ww  .j  a va  2  s.c om*/
 * @throws Exception 
 */

public void transform(Document xmlDoc, InputStream styleIn, OutputStream out) throws Exception {

    if (styleIn == null)
        throw new ServletException("No stylesheet configued");

    JDOMSource source = new JDOMSource(xmlDoc);
    StreamResult result = new StreamResult(out);

    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Templates stylesheet = tFactory.newTemplates(new StreamSource(styleIn));
        Transformer processor = stylesheet.newTransformer();
        processor.transform(source, result);

    } catch (Exception ex) {
        log.error(ex.getMessage());
        throw new Exception("XSLTTransformer Exception: " + ex.getMessage());
    }
}

From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPQuery.java

/**
 * Generates an XML or HTML document based on a given stylesheet
 * @param xmlDoc Specifies the xml document
 * @param styleIn specifies the stylesheet
 * @return/*from www .  j a va  2  s .  c o m*/
 * @throws Exception 
 */

public Document XSLTTransformer(Document xmlDoc, InputStream styleIn) throws Exception {
    JDOMSource source = new JDOMSource(xmlDoc);
    JDOMResult result = new JDOMResult();
    try {
        if (styleIn != null) {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Templates stylesheet = tFactory.newTemplates(new StreamSource(styleIn));
            Transformer processor = stylesheet.newTransformer();
            processor.transform(source, result);
        }

    } catch (Exception ex) {
        log.error(ex.getMessage());
        throw new Exception("XSLTTransformer Exception: " + ex.getMessage());
    }
    return result.getDocument();
}

From source file:Examples.java

/**
 * Show how to transform a DOM tree into another DOM tree.
 * This uses the javax.xml.parsers to parse an XML file into a
 * DOM, and create an output DOM.//from  w  w  w. java2  s  .c  o m
 */
public static Node exampleDOM2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    if (tfactory.getFeature(DOMSource.FEATURE)) {
        Templates templates;

        {
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            dfactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            org.w3c.dom.Document outNode = docBuilder.newDocument();
            Node doc = docBuilder.parse(new InputSource(xslID));

            DOMSource dsource = new DOMSource(doc);
            // If we don't do this, the transformer won't know how to 
            // resolve relative URLs in the stylesheet.
            dsource.setSystemId(xslID);

            templates = tfactory.newTemplates(dsource);
        }

        Transformer transformer = templates.newTransformer();
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        // Note you must always setNamespaceAware when building .xsl stylesheets
        dfactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();
        Node doc = docBuilder.parse(new InputSource(sourceID));

        transformer.transform(new DOMSource(doc), new DOMResult(outNode));

        Transformer serializer = tfactory.newTransformer();
        serializer.transform(new DOMSource(outNode), new StreamResult(new OutputStreamWriter(System.out)));

        return outNode;
    } else {
        throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!");
    }
}

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Get an XSLT Templates object from an XSLT Resource.
 * /*w  ww. j  a v a2s . c  o  m*/
 * @param resource
 *        the XSLT Resource to load
 * @return the compiled Templates
 */
public Templates getTemplates(Resource resource) {
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        return tf.newTemplates(new StreamSource(resource.getInputStream()));
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Unable to load XSLT from resource [" + resource + ']');
    } catch (IOException e) {
        throw new RuntimeException("Unable to load XSLT from resource [" + resource + ']');
    }
}

From source file:be.ibridge.kettle.job.entry.xslt.JobEntryXSLT.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);/*from   w  w  w.  j a  v  a  2  s. c om*/

    String realxmlfilename = getRealxmlfilename();
    String realxslfilename = getRealxslfilename();
    String realoutputfilename = getRealoutputfilename();

    FileObject xmlfile = null;
    FileObject xlsfile = null;
    FileObject outputfile = null;

    try

    {

        if (xmlfilename != null && xslfilename != null && outputfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);
            xlsfile = KettleVFS.getFileObject(realxslfilename);
            outputfile = KettleVFS.getFileObject(realoutputfilename);

            if (xmlfile.exists() && xlsfile.exists()) {
                if (outputfile.exists() && iffileexists == 2) {
                    //Output file exists
                    // User want to fail
                    log.logError(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                            + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(false);
                    result.setNrErrors(1);

                }

                else if (outputfile.exists() && iffileexists == 1) {
                    // Do nothing
                    log.logDebug(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                            + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(true);
                } else {

                    if (outputfile.exists() && iffileexists == 0) {
                        // the zip file exists and user want to create new one with unique name
                        //Format Date

                        DateFormat dateFormat = new SimpleDateFormat("mmddyyyy_hhmmss");
                        // Try to clean filename (without wildcard)
                        String wildcard = realoutputfilename.substring(realoutputfilename.length() - 4,
                                realoutputfilename.length());
                        if (wildcard.substring(0, 1).equals(".")) {
                            // Find wildcard         
                            realoutputfilename = realoutputfilename.substring(0,
                                    realoutputfilename.length() - 4) + "_" + dateFormat.format(new Date())
                                    + wildcard;
                        } else {
                            // did not find wilcard
                            realoutputfilename = realoutputfilename + "_" + dateFormat.format(new Date());
                        }
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileNameChange1.Label")
                                        + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileNameChange2.Label"));

                    }

                    //String xmlSystemXML = new File(realxmlfilename).toURL().toExternalForm(  );
                    //String xsltSystemXSL = new File(realxslfilename).toURL().toExternalForm(  );

                    // Create transformer factory
                    TransformerFactory factory = TransformerFactory.newInstance();

                    // Use the factory to create a template containing the xsl file
                    Templates template = factory
                            .newTemplates(new StreamSource(new FileInputStream(realxslfilename)));

                    // Use the template to create a transformer
                    Transformer xformer = template.newTransformer();

                    // Prepare the input and output files
                    Source source = new StreamSource(new FileInputStream(realxmlfilename));
                    StreamResult resultat = new StreamResult(new FileOutputStream(realoutputfilename));

                    // Apply the xsl file to the source file and write the result to the output file
                    xformer.transform(source, resultat);

                    // Everything is OK
                    result.setResult(true);
                }
            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxmlfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                if (!xlsfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxslfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryXSLT.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }

    }

    catch (Exception e) {

        log.logError(toString(),
                Messages.getString("JobEntryXSLT.ErrorXLST.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML1.Label") + realxmlfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML2.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL1.Label") + realxslfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (xlsfile != null)
                xlsfile.close();
            if (outputfile != null)
                outputfile.close();

        } catch (IOException e) {
        }
    }

    return result;
}

From source file:it.geosolutions.geobatch.task.TaskExecutor.java

private String buildArgument(final Source xmlSource, final InputStream is) throws TransformerException {
    // XML parsing to setup a command line
    final TransformerFactory f = TransformerFactory.newInstance();
    final StringWriter result = new StringWriter();
    final Templates transformation = f.newTemplates(new StreamSource(is));
    final Transformer transformer = transformation.newTransformer();
    transformer.transform(xmlSource, new StreamResult(result));
    final String argument = result.toString().replace("\n", " ");
    return argument;
}

From source file:org.ambraproject.admin.service.impl.DocumentManagementServiceImpl.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   ww w  .java 2 s  . co m*/
 */
private Transformer getTranslet(Document doc) throws TransformerException {
    Transformer transformer;
    StreamSource templateStream = null;
    String templateName;
    try {
        String key = doc.getDocumentElement().getAttribute("dtd-version").trim();
        if ((doc == null) || (!xslTemplateMap.containsKey(key)) || (key.equalsIgnoreCase(""))) {
            templateStream = getAsStream(xslDefaultTemplate);
        } else {
            templateName = xslTemplateMap.get(key);
            templateStream = getAsStream(templateName);
        }
    } catch (Exception e) {
        log.error("XmlTransform not found", e);
    }

    final TransformerFactory tFactory = TransformerFactory.newInstance();
    Templates translet = tFactory.newTemplates(templateStream);
    transformer = translet.newTransformer();
    return transformer;
}