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

public static Document styleDocument(Document document, String stylesheet, boolean xslInPath,
        Map<String, Object> parameters) throws Exception {

    Transformer transformer = XmlUtils.getTransformer(stylesheet, xslInPath);
    if (parameters != null) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }//from  ww  w  .java2  s. c  o m
    }
    // now lets style the given document
    DocumentSource source = new DocumentSource(document);
    DocumentResult result = new DocumentResult();
    transformer.transform(source, result);
    // return the transformed document
    return result.getDocument();
}

From source file:XmlUtils.java

public static void styleDocument(Document document, String stylesheet, boolean xslInPath,
        Map<String, Object> parameters, OutputStream out) throws Exception {

    Transformer transformer = XmlUtils.getTransformer(stylesheet, xslInPath);
    if (parameters != null) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }//ww  w  .  j a v  a2  s  .co  m
    }
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    DocumentSource source = new DocumentSource(document);
    // now lets style the given document

    StreamResult sresult = new StreamResult(out);
    transformer.transform(source, sresult);

}

From source file:info.mikaelsvensson.devtools.report.xslt.XSLTReport.java

private static void writeFile(Document input, File output, Source xsltSource, Map<String, String> parameters)
        throws TransformerException {
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xsltSource);
    StreamResult outputTarget = new StreamResult(output);

    Source xmlSource = new DOMSource(input);
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        transformer.setParameter(entry.getKey(), entry.getValue());
    }//  w w w . j a va  2s.c o m

    transformer.setParameter("outputFile", output.getName());
    transformer.transform(xmlSource, outputTarget);
}

From source file:Main.java

/**
 * Applies a stylesheet (that receives parameters) to a given xml document.
 *
 * @param xmlDocument  the xml document to be transformed
 * @param parameters   the hashtable with the parameters to be passed to the
 *                     stylesheet//  w w w.  ja  va  2 s. c  o  m
 * @param xsltFilename the filename of the stylesheet
 * @return the transformed xml document
 * @throws Exception
 */
public static Document transformDocument(Document xmlDocument, Map<String, String> parameters,
        String xsltFilename) throws TransformerException, ParserConfigurationException {

    File xslFile = new File(xsltFilename);
    if (xslFile.exists()) {

        // Generate a Transformer.
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(new StreamSource(xsltFilename));

        if (transformer != null) {

            // set transformation parameters
            if (parameters != null) {
                for (Map.Entry<String, String> param : parameters.entrySet()) {
                    transformer.setParameter(param.getKey(), param.getValue());
                }
            }

            // Create an empty DOMResult object for the output.
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            dFactory.setNamespaceAware(true);
            DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
            Document dstDocument = dBuilder.newDocument();

            DOMResult domResult = new DOMResult(dstDocument);

            // Perform the transformation.
            transformer.transform(new DOMSource(xmlDocument), domResult);
            // Now you can get the output Node from the DOMResult.
            return dstDocument;
        }
    }
    return null;
}

From source file:Main.java

private static void transformInternal(final URIResolver xslResolver, final StreamSource xml,
        final InputSource xsl, final Map<String, Object> parameters, final StreamResult result)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerException {//w w  w.j ava  2 s  . c om
    final TransformerFactory tfactory = TransformerFactory.newInstance();
    tfactory.setURIResolver(xslResolver);

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // if so, we can safely cast
        final SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // create a Templates ContentHandler to handle parsing of the
        // stylesheet
        final javax.xml.transform.sax.TemplatesHandler templatesHandler = stfactory.newTemplatesHandler();
        templatesHandler.setDocumentLocator(emptyDocumentLocator);

        final XMLFilter filter = new XMLFilterImpl();
        filter.setParent(makeXMLReader());
        filter.setContentHandler(templatesHandler);

        // parse the stylesheet
        templatesHandler.setSystemId(xsl.getSystemId());
        filter.parse(xsl);

        // set xslt parameters
        final Transformer autobot = templatesHandler.getTemplates().newTransformer();
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                final String name = keys.next();
                final Object value = parameters.get(name);
                autobot.setParameter(name, value);
            }
        }

        // set saxon parameters
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                String name = keys.next();
                if (name.startsWith("saxon-")) {
                    final String value = parameters.get(name).toString();
                    name = name.replaceFirst("saxon\\-", "");
                    autobot.setOutputProperty(name, value);
                }
            }
        }

        // do the transform
        // logger.debug("SAX resolving systemIDs relative to: " +
        // templatesHandler.getSystemId());
        autobot.transform(xml, result);

    } else {
        throw new IllegalStateException("Factory doesn't implement SAXTransformerFactory");
    }
}

From source file:Main.java

/**
 * General method for transformation to text. Transform a Source
 * document using a Source XSL document and an array of parameters.
 * The parameter array consists of a sequence of pairs of (String parametername)
 * followed by (Object parametervalue) in an Object[].
 * @param doc the document to transform.
 * @param xsl the XSL transformation program.
 * @param params the array of transformation parameters.
 * @return the transformed text./*from ww  w.  ja va2 s .  c o  m*/
 */
public static String getTransformedText(Source doc, Source xsl, Object[] params) throws Exception {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xsl);
    if ((params != null) && (params.length > 1)) {
        for (int i = 0; i < params.length; i = i + 2) {
            transformer.setParameter((String) params[i], params[i + 1]);
        }
    }
    StringWriter sw = new StringWriter();
    transformer.transform(doc, new StreamResult(sw));
    return sw.toString();
}

From source file:Main.java

/**
 * Use the transform specified by xslSrc and transform the document specified by docSrc, and return the resulting
 * document./*from   w w  w.java2s .  c  om*/
 * 
 * @param xslSrc
 *          StreamSrc containing the xsl transform
 * @param docSrc
 *          StreamSrc containing the document to be transformed
 * @param params
 *          Map of properties to set on the transform
 * @param resolver
 *          URIResolver instance to resolve URI's in the output document.
 * 
 * @return StringBuffer containing the XML results of the transform
 * @throws TransformerConfigurationException
 *           if the TransformerFactory fails to create a Transformer.
 * @throws TransformerException
 *           if actual transform fails.
 */
protected static final StringBuffer transformXml(final StreamSource xslSrc, final StreamSource docSrc,
        final Map params, final URIResolver resolver)
        throws TransformerConfigurationException, TransformerException {

    StringBuffer sb = null;
    StringWriter writer = new StringWriter();

    TransformerFactory tf = TransformerFactory.newInstance();
    if (null != resolver) {
        tf.setURIResolver(resolver);
    }
    // TODO need to look into compiling the XSLs...
    Transformer t = tf.newTransformer(xslSrc); // can throw
    // TransformerConfigurationException
    // Start the transformation
    if (params != null) {
        Set<?> keys = params.keySet();
        Iterator<?> it = keys.iterator();
        String key, val;
        while (it.hasNext()) {
            key = (String) it.next();
            val = (String) params.get(key);
            if (val != null) {
                t.setParameter(key, val);
            }
        }
    }
    t.transform(docSrc, new StreamResult(writer)); // can throw
    // TransformerException
    sb = writer.getBuffer();

    return sb;
}

From source file:Main.java

/**
 * This method performs XSL Transformation. <br>
 * <b>Deprecated use XmlTransformer.transform</b>
 * //from   w  w  w .  j a v a  2s .  c o  m
 * @param source
 *            The input XML document
 * @param stylesheet
 *            The XSL stylesheet
 * @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
 */
@Deprecated
public static String transform(Source source, Source stylesheet, Map<String, String> params,
        Properties outputProperties) throws Exception {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(stylesheet);

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

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

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

        StringWriter sw = new StringWriter();
        Result result = new StreamResult(sw);
        transformer.transform(source, result);

        return sw.toString();
    } 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:Main.java

public static Node xsltTransform(InputStream styleSheet, Document response, Map<String, String> params) {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {//from w w  w  .  j ava 2 s .c o  m
        javax.xml.transform.stream.StreamSource streamSource = new javax.xml.transform.stream.StreamSource(
                styleSheet);
        transformer = tFactory.newTransformer(streamSource);
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (Iterator<String> iterator = params.keySet().iterator(); iterator.hasNext();) {
        String key = iterator.next();
        String value = params.get(key);
        transformer.setParameter(key, value);
    }

    Source xmlSource = new DOMSource(response);
    DOMResult result = new DOMResult();
    try {
        transformer.transform(xmlSource, result);
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result.getNode();
}

From source file:de.betterform.agent.web.WebUtil.java

/**
 * transforms an input document and writes it to the ServletOutputStream.
 *
 * @param context the servlet context//from  w w  w  . j  a  v  a 2  s .  c om
 * @param response the servlet response
 * @param input an DOM input document to transform
 * @param stylesheetName the name of the stylesheet to use. This must be preloaded in CachingTransformerService. See WebFactory
 * @param params transformation parameters as a piece of DOM if any. The params object is passed as param 'params' to the stylesheets
 * @throws java.io.IOException
 */
public static void doTransform(ServletContext context, HttpServletResponse response, Document input,
        String stylesheetName, Object params) throws IOException {
    CachingTransformerService transformerService = (CachingTransformerService) context
            .getAttribute(TransformerService.TRANSFORMER_SERVICE);
    Source xmlSource = new DOMSource(input);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        Transformer transformer = transformerService.getTransformerByName(stylesheetName);
        if (params != null) {
            if (params instanceof Node) {
                transformer.setParameter("params", params);
            }
        }
        transformer.transform(xmlSource, new StreamResult(outputStream));

    } catch (TransformerException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    response.setContentType(WebUtil.HTML_CONTENT_TYPE);
    response.setContentLength(outputStream.toByteArray().length);
    response.getOutputStream().write(outputStream.toByteArray());
    response.getOutputStream().close();
}