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: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  ww  w  .  j  a  v a  2 s . c  o 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;
}

From source file:net.sf.joost.trax.TransformerFactoryImpl.java

/**
 * Gets a <code>TransformerHandler</code> object that can process
 * SAX ContentHandler events into a Result, based on the Templates argument.
 * Implementation of the {@link SAXTransformerFactory}
 * @param templates - The compiled transformation instructions.
 * @return {@link TransformerHandler} ready to transform SAX events.
 * @throws TransformerConfigurationException
 *//*from  w w w. j  ava 2s  . c  om*/
public TransformerHandler newTransformerHandler(Templates templates) throws TransformerConfigurationException {

    synchronized (reentryGuard) {
        if (DEBUG)
            log.debug("get a TransformerHandler-instance from Templates");
        Transformer internal = templates.newTransformer();
        TransformerHandlerImpl thandler = new TransformerHandlerImpl(internal);
        return thandler;
    }
}

From source file:com.panet.imeta.job.entries.xslt.JobEntryXSLT.java

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

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

    FileObject xmlfile = null;
    FileObject xslfile = null;
    FileObject outputfile = null;

    try

    {

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

            if (xmlfile.exists() && xslfile.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
                    if (log.isDebug())
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(true);
                } else {
                    if (outputfile.exists() && iffileexists == 0) {
                        // the output file exists and user want to create new one with unique name
                        //Format Date

                        // 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) + "_"
                                    + StringUtil.getFormattedDateTimeNow(true) + wildcard;
                        } else {
                            // did not find wildcard
                            realoutputfilename = realoutputfilename + "_"
                                    + StringUtil.getFormattedDateTimeNow(true);
                        }
                        if (log.isDebug())
                            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"));
                    }

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

                    if (xsltfactory.equals(FACTORY_SAXON)) {
                        // Set the TransformerFactory to the SAXON implementation.
                        factory = new net.sf.saxon.TransformerFactoryImpl();
                    }

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerFactoryInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerFactory", factory.getClass().getName()));

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

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

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerClassInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerClass", xformer.getClass().getName()));

                    // Prepare the input and output files
                    Source source = new StreamSource(KettleVFS.getInputStream(xmlfile));
                    StreamResult resultat = new StreamResult(KettleVFS.getOutputStream(outputfile, false));

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

                    if (isAddFileToResult()) {
                        // Add output filename to output files
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                KettleVFS.getFileObject(realoutputfilename), parentJob.getJobname(),
                                toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    // 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 (!xslfile.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 (xslfile != null)
                xslfile.close();
            if (outputfile != null)
                outputfile.close();

            // file object is not properly garbaged collected and thus the file cannot
            // be deleted anymore. This is a known problem in the JVM.

            System.gc();
        } catch (IOException e) {
        }
    }

    return result;
}

From source file:ddf.services.schematron.SchematronValidationService.java

private SchematronReport generateReport(String metadata, Templates validator)
        throws SchematronValidationException {

    XMLReader xmlReader = null;/*  w w w  . ja va 2  s  . co m*/
    try {
        XMLReader xmlParser = XML_UTILS.getSecureXmlParser();
        xmlReader = new XMLFilterImpl(xmlParser);
    } catch (SAXException e) {
        throw new SchematronValidationException(e);
    }

    SchematronReport report;
    try {
        Transformer transformer = validator.newTransformer();
        DOMResult schematronResult = new DOMResult();
        transformer.transform(new SAXSource(xmlReader, new InputSource(new StringReader(metadata))),
                schematronResult);
        report = new SvrlReport(schematronResult);
    } catch (TransformerException e) {
        throw new SchematronValidationException("Could not setup validator to perform validation.", e);
    }
    return report;
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

public void getObjectProfile(Context context, String PID, Date asOfDateTime, boolean xml,
        HttpServletRequest request, HttpServletResponse response) throws ServerException {

    OutputStreamWriter out = null;
    Date versDateTime = asOfDateTime;
    ObjectProfile objProfile = null;/*  ww w  .  j  a  v  a  2s.  c  o  m*/
    PipedWriter pw = null;
    PipedReader pr = null;
    try {
        pw = new PipedWriter();
        pr = new PipedReader(pw);
        objProfile = m_access.getObjectProfile(context, PID, asOfDateTime);
        if (objProfile != null) {
            // Object Profile found.
            // Serialize the ObjectProfile object into XML
            new ProfileSerializerThread(context, PID, objProfile, versDateTime, pw).start();
            if (xml) {
                // Return results as raw XML
                response.setContentType(CONTENT_TYPE_XML);

                // Insures stream read from PipedReader correctly translates
                // utf-8
                // encoded characters to OutputStreamWriter.
                out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                char[] buf = new char[BUF];
                int len = 0;
                while ((len = pr.read(buf, 0, BUF)) != -1) {
                    out.write(buf, 0, len);
                }
                out.flush();
            } else {
                // Transform results into an html table
                response.setContentType(CONTENT_TYPE_HTML);
                out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                File xslFile = new File(m_server.getHomeDir(), "access/viewObjectProfile.xslt");
                Templates template = XmlTransformUtility.getTemplates(xslFile);
                Transformer transformer = template.newTransformer();
                transformer.setParameter("fedora", context.getEnvironmentValue(FEDORA_APP_CONTEXT_NAME));
                transformer.transform(new StreamSource(pr), new StreamResult(out));
            }
            out.flush();

        } else {
            throw new GeneralException("No object profile returned");
        }
    } catch (ServerException e) {
        throw e;
    } catch (Throwable th) {
        String message = "Error getting object profile";
        logger.error(message, th);
        throw new GeneralException(message, th);
    } finally {
        try {
            if (pr != null) {
                pr.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Throwable th) {
            String message = "Error closing output";
            logger.error(message, th);
            throw new StreamIOException(message);
        }
    }
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.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.ja  va 2s . c  om*/
private Transformer getTranslet(Document doc) throws TransformerException, URISyntaxException {
    final TransformerFactory tFactory = TransformerFactory.newInstance(); // key is "" if the Attribute does not exist
    InputStream templateStream;

    String key = doc.getDocumentElement().getAttribute("dtd-version").trim();
    if ((doc == null) || (!xslTemplateMap.containsKey(key)) || (key.equalsIgnoreCase(""))) {
        templateStream = xslDefaultTemplate;
    } else {
        String templateName = xslTemplateMap.get(key);
        templateStream = getAsStream(templateName);
    }

    Templates translet = tFactory.newTemplates(new StreamSource(templateStream));
    return translet.newTransformer();
}

From source file:edu.unc.lib.dl.schematron.SchematronValidator.java

/**
 * Use this to initialize the configured schemas. Generate stylesheet
 * implementations of ISO Schematron files and preload them into Transformer
 * Templates for quick use./*from ww  w .ja  v  a 2s . c om*/
 */
public void loadSchemas() {
    templates = new HashMap<String, Templates>();
    // Load up a transformer and the ISO Schematron to XSL templates.
    Templates isoSVRLTemplates = null;
    ClassPathResource svrlRes = new ClassPathResource("/edu/unc/lib/dl/schematron/iso_svrl.xsl",
            SchematronValidator.class);
    Source svrlrc;
    try {
        svrlrc = new StreamSource(svrlRes.getInputStream());
    } catch (IOException e1) {
        throw new Error("Cannot load iso_svrl.xsl", e1);
    }
    TransformerFactory factory = null;
    try {
        factory = new TransformerFactoryImpl();
        // enable relative classpath-based URIs
        factory.setURIResolver(new URIResolver() {
            public Source resolve(String href, String base) throws TransformerException {
                ClassPathResource svrlRes = new ClassPathResource(href, SchematronValidator.class);
                Source result;
                try {
                    result = new StreamSource(svrlRes.getInputStream());
                } catch (IOException e1) {
                    throw new TransformerException("Cannot resolve " + href, e1);
                }
                return result;
            }
        });
        isoSVRLTemplates = factory.newTemplates(svrlrc);
    } catch (TransformerFactoryConfigurationError e) {
        log.error("Error setting up transformer factory.", e);
        throw new Error("Error setting up transformer factory", e);
    } catch (TransformerConfigurationException e) {
        log.error("Error setting up transformer.", e);
        throw new Error("Error setting up transformer", e);
    }

    // Get a transformer
    Transformer t = null;
    try {
        t = isoSVRLTemplates.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Error("There was a problem configuring the transformer.", e);
    }

    for (String schema : schemas.keySet()) {
        // make XSLT out of Schematron for each schema
        Resource resource = schemas.get(schema);
        Source schematron = null;
        try {
            schematron = new StreamSource(resource.getInputStream());
        } catch (IOException e) {
            throw new Error("Cannot load resource for schema \"" + schema + "\" at " + resource.getDescription()
                    + resource.toString());
        }
        JDOMResult res = new JDOMResult();
        try {
            t.transform(schematron, res);
        } catch (TransformerException e) {
            throw new Error("Schematron issue: There were problems transforming Schematron to XSL.", e);
        }

        // compile templates object for each profile
        try {
            Templates schemaTemplates = factory.newTemplates(new JDOMSource(res.getDocument()));
            templates.put(schema, schemaTemplates);
        } catch (TransformerConfigurationException e) {
            throw new Error("There was a problem configuring the transformer.", e);
        }
    }

}

From source file:net.wastl.webmail.ui.xml.XHTMLDocument.java

public XHTMLDocument(Document xml, Templates stylesheet) throws WebMailException {
    StringWriter writer = new StringWriter();

    long start_t = System.currentTimeMillis();
    try {//from  w  w  w.ja  v  a 2  s.  c  o  m
        DOMSource msg_xml = new DOMSource((Node) xml);
        StreamResult msg_result = new StreamResult(writer);

        Transformer processor = stylesheet.newTransformer();
        processor.transform(msg_xml, msg_result);
    } catch (Exception ex) {
        log.error("Error transforming XML to XHTML.", ex);
        throw new WebMailException("Error transforming XML to XHTML: " + ex);
    }
    long end_t = System.currentTimeMillis();
    log.debug("Transformation (with precompiled stylesheet) XML --> XHTML took " + (end_t - start_t) + " ms.");

    content = writer.toString();
}