Example usage for javax.xml.transform Transformer setParameter

List of usage examples for javax.xml.transform Transformer setParameter

Introduction

In this page you can find the example usage for javax.xml.transform Transformer setParameter.

Prototype

public abstract void setParameter(String name, Object value);

Source Link

Document

Add a parameter for the transformation.

Usage

From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java

public static void transformToFile(final File targetFile, final boolean asXml, final Document doc)
        throws TransformerConfigurationException, TransformerException, IOException {
    Transformer transformer;
    Config config = CoverageReport.getConfig();
    if (asXml) {//from   w ww.  j a va 2  s .c  o m
        transformer = getTransformer(null);
    } else {
        transformer = getTransformer('/' + JGenHtmlUtils.XSLT_NAME);
        transformer.setParameter("ext", config.getHtmlExt());
        File cssFile = config.getCssFile();
        if (cssFile != null) {
            transformer.setParameter("cssName", cssFile.getName());
        }
    }
    DOMSource src = new DOMSource(doc);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StreamResult res;
    if (config.isGzip()) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(targetFile));
        res = new StreamResult(bos);
        transformer.transform(src, res);
        IOUtils.write(bos.toByteArray(), gzos);
        IOUtils.closeQuietly(gzos);
    } else {
        res = new StreamResult(targetFile);
        transformer.transform(src, res);
    }
}

From source file:Examples.java

/**
 * Show the that a transformer can be reused, and show resetting 
 * a parameter on the transformer./*  w w  w .java 2s  .c o  m*/
 */
public static void exampleTransformerReuse(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException {
    // Create a transform factory instance.
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Create a transformer for the stylesheet.
    Transformer transformer = tfactory.newTransformer(new StreamSource(xslID));

    transformer.setParameter("a-param", "hello to you!");

    // Transform the source XML to System.out.
    transformer.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));

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

    transformer.setParameter("a-param", "hello to me!");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Transform the source XML to System.out.
    transformer.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));
}

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./*from www  .jav a2 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:Transform.java

public static void singlePage() throws Exception {
    InputStream isXML = Transform.class.getResourceAsStream(file("manual.xml"));
    InputStream isXSL = Transform.class.getResourceAsStream("html-page.xsl");

    StreamSource xsl = new StreamSource(isXSL);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xsl);

    String relativePath = relative(path("manual-single-page"));
    String root = root();/* w ww . j  a v a  2  s  . c  o m*/
    Match manual = $(isXML);
    replaceVariables(manual);

    File dir = new File(path("manual-single-page"));
    dir.mkdirs();

    System.out.println("Transforming manual");
    File file = new File(dir, "index.php");
    file.delete();
    FileOutputStream out = new FileOutputStream(file);

    Source source = new DOMSource(manual.document());
    Result target = new StreamResult(out);

    transformer.setParameter("relativePath", relativePath);
    transformer.setParameter("root", root);
    transformer.transform(source, target);

    out.close();
}

From source file:com.moviejukebox.writer.MovieJukeboxHTMLWriter.java

/**
 * Creates and caches Transformer, one for every thread/xsl file.
 *
 * @param xslFile/*from   w  w w.ja va  2  s.c  om*/
 * @param styleSheetTargetRootPath
 * @return
 */
public static Transformer getTransformer(File xslFile, String styleSheetTargetRootPath) {
    /*
     * Removed caching of transformer, as saxon keeps all parsed documents in memory, causing memory leaks.
     * Creating a new transformer every time doesn't consume too much time and has no impact on performance.
     * It lets YAMJ save lot of memory.
     * @author Vincent
     */
    Source xslSource = new StreamSource(xslFile);

    // Sometimes the StreamSource doesn't return an object and we get a null pointer exception, so check it and try loading it again
    for (int looper = 1; looper < 5; looper++) {
        xslSource = new StreamSource(xslFile);
        if (xslSource != null) {
            // looks ok, so quit the loop
            break;
        }
    }

    Transformer transformer = null;
    try {
        transformer = TRANSFORMER.newTransformer(xslSource);
        transformer.setParameter("homePage", INDEX_HTML_FILE);
        transformer.setParameter("rootPath",
                new File(styleSheetTargetRootPath).getAbsolutePath().replace('\\', '/'));
        for (Entry<Object, Object> e : PropertiesUtil.getEntrySet()) {
            if (e.getKey() != null && e.getValue() != null) {
                transformer.setParameter(e.getKey().toString(), e.getValue().toString());
            }
        }
    } catch (TransformerConfigurationException ex) {
        LOG.error("Failed to get transformer for XSL: " + xslFile.getAbsolutePath());
        LOG.warn(SystemTools.getStackTrace(ex));
    }
    return transformer;
}

From source file:ddf.util.XSLTUtil.java

/**
 * Performs an xsl transformation against an XML document
 *
 * @param template/*from  w w w  .  j  a  v  a  2s .com*/
 *            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:com.portfolio.data.utils.DomUtils.java

public static String processXSLTfile2String(Document xml, String xslFile, String param[], String paramVal[],
        StringBuffer outTrace) throws Exception {
    //  =======================================
    outTrace.append("<br>-->processXSLTfile2String-" + xslFile);
    Transformer transformer = TransformerFactory.newInstance()
            .newTransformer(new StreamSource(new File(xslFile)));
    outTrace.append(".1");
    StreamResult result = new StreamResult(new StringWriter());
    outTrace.append(".2");
    DOMSource source = new DOMSource(xml);
    outTrace.append(".3");
    for (int i = 0; i < param.length; i++) {
        outTrace.append("<br>setParemater - " + param[i] + ":" + paramVal[i] + "...");
        transformer.setParameter(param[i], paramVal[i]);
        outTrace.append("ok");
    }//w w  w.  ja va 2 s . c om
    outTrace.append(".4");
    transformer.transform(source, result);
    outTrace.append("<br><--processXSLTfile2String-" + xslFile);
    return result.getWriter().toString();
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLFilteringService.java

/**
 * Runs XSLT based upon specified inputs and returns the outputfile.
 *
 * TODO: Need some refactoring to make this reusable throughout OMAR
 * particularly in CanonicalXMLCatalogingService.
 *//*from  w w w. j a  v  a2  s  . co  m*/
protected static File runXSLT(StreamSource input, StreamSource xslt, URIResolver resolver,
        HashMap<String, String> params) throws RegistryException {

    File outputFile = null;

    try {
        //dumpStream(xslt);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = initTransformer(tFactory, xslt);
        // Use FilteringService URIResolver to resolve RIs submitted in the
        // ServiceInput object
        transformer.setURIResolver(resolver);
        //Set respository item as parameter

        //Create the output file with the filtered RegistryObject Metadata
        outputFile = File.createTempFile("CanonicalXMLFilteringService_Output", ".xml");
        outputFile.deleteOnExit();

        log.debug("outputFile= " + outputFile.getAbsolutePath());

        Iterator<String> iter = params.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = params.get(key);
            transformer.setParameter(key, value);
        }

        StreamResult sr = new StreamResult(outputFile);
        transformer.transform(input, sr);

    } catch (Exception e) {
        throw new RegistryException(e);
    }

    return outputFile;

}

From source file:fr.paris.lutece.plugins.calendar.service.XMLUtils.java

/**
 * This method performs XSL Transformation.
 * /*from  www . ja v a2  s. co  m*/
 * @param strXml The input XML document
 * @param baSource The source input stream
 * @param params parameters to apply to the XSL Stylesheet
 * @param outputProperties properties to use for the xsl transform. Will
 *            overload the xsl output definition.
 * @return The output document transformed
 * @throws Exception The exception
 */
public static byte[] transformXMLToXSL(String strXml, InputStream baSource, Map<String, String> params,
        Properties outputProperties) throws Exception {
    Source stylesheet = new StreamSource(baSource);
    StringReader srInputXml = new StringReader(strXml);
    StreamSource source = new StreamSource(srInputXml);

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(stylesheet);

        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }

        if (params != null) {
            transformer.clearParameters();

            Set<Entry<String, String>> entries = params.entrySet();

            for (Entry<String, String> entry : entries) {
                String name = entry.getKey();
                String value = entry.getValue();
                transformer.setParameter(name, value);
            }
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result result = new StreamResult(out);
        transformer.transform(source, result);

        return out.toByteArray();
    } catch (TransformerConfigurationException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (TransformerFactoryConfigurationError e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    } catch (TransformerException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (Exception e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    }
}

From source file:dk.statsbiblioteket.util.xml.XSLT.java

/**
 * Assigns the given parameters to the given Transformer. Previously assigned parameters are cleared first.
 * @param transformer an existing transformer.
 * @param parameters key-value pairs for parameters to assign.
 * @return the given transformer, with the given parameters assigned.
 */// w  ww.jav  a 2  s.  c o m
public static Transformer assignParameters(Transformer transformer, Map parameters) {
    transformer.clearParameters(); // Is this safe? Any defaults lost?
    if (parameters != null) {
        for (Object entryObject : parameters.entrySet()) {
            Map.Entry entry = (Map.Entry) entryObject;
            transformer.setParameter((String) entry.getKey(), entry.getValue());
        }
    }
    return transformer;
}