Example usage for javax.xml.transform Transformer clearParameters

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

Introduction

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

Prototype

public abstract void clearParameters();

Source Link

Document

Clear all parameters set with setParameter.

Usage

From source file:Main.java

/**
 * This method performs XSL Transformation. <br>
 * <b>Deprecated use XmlTransformer.transform</b>
 * //from www .j  a v a  2 s  . co  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:fr.paris.lutece.plugins.calendar.service.XMLUtils.java

/**
 * This method performs XSL Transformation.
 * /*from  ww w  . ja v a  2  s. com*/
 * @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.
 *///from   ww  w  .ja  va  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;
}

From source file:com.predic8.membrane.core.interceptor.xslt.XSLTTransformer.java

public byte[] transform(Source xml, Map<String, String> parameters) throws Exception {
    log.debug("applying transformation: " + styleSheet);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Transformer t = transformers.take();
    try {//from w w  w  .j  a v  a 2  s.  c  om
        try {
            t.clearParameters();
        } catch (NullPointerException e) {
            // do nothing
        }
        for (Map.Entry<String, String> e : parameters.entrySet()) {
            t.setParameter(e.getKey(), e.getValue());
        }
        t.transform(xml, new StreamResult(baos));
    } finally {
        transformers.put(t);
    }
    return baos.toByteArray();
}

From source file:net.sf.joost.plugins.traxfilter.THResolver.java

/**
 * Prepare TH instance for work/*from  w w  w  . j  ava 2 s  . co m*/
 *
 * This involves setting TrAX parameters and all other stuff if needed
 *
 * @param th
 * @param params
 */
protected void prepareTh(TransformerHandler th, Hashtable params) {
    if (DEBUG)
        log.debug("prepareTh()");

    Transformer tr = th.getTransformer();

    // make sure old parameters are cleaned
    tr.clearParameters();

    // set transformation parameters
    if (!params.isEmpty()) {
        for (Enumeration e = params.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            if (DEBUG)
                log.debug("prepareTh(): set parameter " + key + "=" + params.get(key));

            if (!key.startsWith(tmp_TRAX_ATTR_NS) && !key.startsWith(tmp_FILTER_ATTR_NS)) {
                // ordinary parameter, set it to the TrAX object
                tr.setParameter(key, params.get(key));
            }
        }
    }
}

From source file:de.escidoc.core.common.util.xml.XmlUtility.java

/**
 * Create the content of the DC datastream to store in Fedora.
 *
 * @param nsUri          nsUri of the md record. Through this URI is the mapping schema selected.
 * @param mdRecordXml    Xml representation of the md record to parse.
 * @param objID          The objid of the Fedora object. A triple is created with this objid.
 * @param contentModelID The objid of the content-model.
 * @return The content of the DC datastream or null if content is empty.
 * @throws WebserverSystemException If an error occurs.
 *//*from ww  w . j  a  va2s . c  o m*/
public static String createDC(final String nsUri, final String mdRecordXml, final CharSequence objID,
        final String contentModelID) throws WebserverSystemException {
    String result = null;
    Transformer t = null;
    final String transformerKey = nsUri + ';' + contentModelID;
    try {
        t = (Transformer) TRANSFORMER_POOL.borrowObject(transformerKey);
        if (objID != null && objID.length() > 0) {
            t.setParameter("ID", objID);
        } else {
            t.clearParameters();
        }
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        t.transform(new StreamSource(new ByteArrayInputStream(mdRecordXml.getBytes(CHARACTER_ENCODING))),
                new StreamResult(out));

        result = out.toString(CHARACTER_ENCODING).trim();
    } catch (final Exception e) {
        throw new WebserverSystemException("Mapping of Metadata to DC failed.", e);
    } finally {
        try {
            TRANSFORMER_POOL.returnObject(transformerKey, t);
        } catch (final Exception e) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Returning transformer to pool failed.");
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Returning transformer to pool failed.", e);
            }
        }
    }
    // check if result is empty
    if (result != null && result.length() == 0) {
        result = null;
    }
    return result;
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

public String xslt(String xml, Transformer t, Map<String, String[]> params, String queryString)
        throws TransformerException {
    if (xml == null) {
        throw new TransformerException("No input document provided");
    }//from w  ww.  j  a v a2  s .  c  o  m
    if (t == null) {
        throw new TransformerException("Null transform");
    }

    // params
    String casGroupTest = getParamString(params, "casGroupTest", null);

    // clear stale parameters
    t.clearParameters();

    // add request params to xsl
    if (params != null) {
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            String val = null;
            String[] vals = (String[]) params.get(key);
            for (int i = 0; i < vals.length; i++) {
                if (vals[i] != null && !vals[i].equals("")) {
                    if (val == null) {
                        val = vals[i];
                    } else {
                        val += "; " + vals[i];
                    }
                }
            }
            if (key != null && val != null) {
                String escaped = StringEscapeUtils.escapeJava(val);
                t.setParameter(key, escaped);
            }
        }
    }
    if (queryString != null) {
        t.setParameter("queryString", StringEscapeUtils.escapeJava(queryString));
    }
    if (casGroupTest != null) {
        t.setParameter("casTest", casGroupTest);
    }
    StringWriter sw = new StringWriter();
    t.transform(new StreamSource(new StringReader(xml)), new StreamResult(sw));
    return sw.toString();
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

/**
 * sets all the parameters of the transformer using a Map with parameter values.
 *///from w  ww  . j  ava 2s . co m
public static void setTransformerParameters(Transformer t, Map parameters) {
    t.clearParameters();
    if (parameters == null) {
        return;
    }
    for (Iterator it = parameters.keySet().iterator(); it.hasNext();) {
        String name = (String) it.next();
        Object value = parameters.get(name);

        if (value != null) {
            t.setParameter(name, value);
            log.debug("setting parameter [" + name + "] on transformer");
        } else {
            log.info("omitting setting of parameter [" + name + "] on transformer, as it has a null-value");
        }
    }
}

From source file:org.apache.cocoon.components.xslt.TraxProcessor.java

public void transform(final Source source, final Source stylesheet, final Parameters params,
        final Result result) throws XSLTProcessorException {
    try {/*ww w  .j a v  a  2 s .  co  m*/
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Transform source = " + source + ", stylesheet = " + stylesheet
                    + ", parameters = " + params + ", result = " + result);
        }
        final TransformerHandler handler = getTransformerHandler(stylesheet);
        if (params != null) {
            final Transformer transformer = handler.getTransformer();
            transformer.clearParameters();
            String[] names = params.getNames();
            for (int i = names.length - 1; i >= 0; i--) {
                transformer.setParameter(names[i], params.getParameter(names[i]));
            }
        }

        handler.setResult(result);
        sourceToSAX(source, handler);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Transform done");
        }
    } catch (SAXException e) {
        // Unwrapping the exception will "remove" the real cause with
        // never Xalan versions and makes the exception message unusable
        final String message = "Error in running Transformation";
        throw new XSLTProcessorException(message, e);
        /*
         * if( e.getException() == null ) { final String message = "Error in
         * running Transformation"; throw new XSLTProcessorException(
         * message, e ); } else { final String message = "Got SAXException.
         * Rethrowing cause exception."; getLogger().debug( message, e );
         * throw new XSLTProcessorException( "Error in running
         * Transformation", e.getException() ); }
         */
    } catch (Exception e) {
        final String message = "Error in running Transformation";
        throw new XSLTProcessorException(message, e);
    }
}

From source file:org.ecoinformatics.export.HtmlToPdfTest.java

/**
 * Test HTML to PDF conversion//  www . ja  va 2s  .  c  om
 */
public void testExport() {
    try {

        // transform EML to HTML

        String srcPath = "src/test/resources/";

        String workingPath = "build/";

        String emlFileName = "eml-sample";

        String emlFileExtension = ".xml";

        String emlFile = srcPath + emlFileName + emlFileExtension;

        String xslFile = "style/eml/eml.xsl";

        String htmlFile = workingPath + emlFileName + ".html";

        // set up the css file
        File cssDir = new File(workingPath + "default");
        if (!cssDir.exists()) {
            cssDir.mkdir();
        }
        File cssFile = new File("default.css");
        File targetCssFile = new File(cssDir, cssFile.getName());
        IOUtils.copy(new FileInputStream(cssFile), new FileOutputStream(targetCssFile));
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(new StreamSource(new File(xslFile)));

        // add some property for style sheet
        transformer.clearParameters();
        transformer.setParameter("href_path_extension", ".html");
        transformer.setParameter("package_id", "test.1.1");
        transformer.setParameter("package_index_name", "metadata");
        transformer.setParameter("qformat", "default");
        transformer.setParameter("entitystyle", "default");
        transformer.setParameter("stylePath", ".");
        transformer.setParameter("displaymodule", "printall");

        transformer.transform(new StreamSource(new File(emlFile)), new StreamResult(new File(htmlFile)));

        // convert HTML to PDF
        String pdfFile = workingPath + emlFileName + ".pdf";

        HtmlToPdf.export(htmlFile, pdfFile);

        // TODO: check that it worked?

    } catch (Exception e) {
        // oops
        e.printStackTrace();
        fail(e.getMessage());
    }

}