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:org.carrot2.source.xml.XmlDocumentSourceHelper.java

/**
 * Returns a Carrot2 XML stream, applying an XSLT transformation if the stylesheet is
 * provided./* w ww .j a v  a2  s . c  om*/
 */
private InputStream getCarrot2XmlStream(InputStream xmlInputStream, Templates stylesheet,
        Map<String, String> xsltParameters)
        throws TransformerConfigurationException, IOException, TransformerException {
    // Perform transformation if stylesheet found.
    InputStream carrot2XmlInputStream;
    if (stylesheet != null) {
        byte[] debugInput = null;
        try {
            // Initialize transformer
            final Transformer transformer = pool.newTransformer(stylesheet);
            final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            // Set XSLT parameters, if any
            if (xsltParameters != null) {
                for (Map.Entry<String, String> entry : xsltParameters.entrySet()) {
                    transformer.setParameter(entry.getKey(), entry.getValue());
                }
            }

            if (log.isDebugEnabled()) {
                debugInput = StreamUtils.readFullyAndClose(xmlInputStream);
                xmlInputStream = new ByteArrayInputStream(debugInput);
            }

            // Perform transformation
            transformer.transform(new StreamSource(xmlInputStream), new StreamResult(outputStream));
            carrot2XmlInputStream = new ByteArrayInputStream(outputStream.toByteArray());
        } catch (TransformerException e) {
            if (debugInput != null) {
                log.debug("Transformer input: " + new String(debugInput, "UTF-8"));
            }
            throw e;
        } finally {
            CloseableUtils.close(xmlInputStream);
        }
    } else {
        carrot2XmlInputStream = xmlInputStream;
    }

    return carrot2XmlInputStream;
}

From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method removes all Spring bean definitions of given type from the XML application context file.
 * @param project//from   w ww. j  a  va 2  s.c o  m
 * @param type
 */
public void removeBeanDefinitions(File configFile, Project project, Class<?> type) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/delete-bean-type.xsl").getInputStream());
        xsltSource.setSystemId("delete-bean");

        List<File> configFiles = new ArrayList<>();
        configFiles.add(configFile);
        configFiles.addAll(getConfigImports(configFile, project));

        for (File file : configFiles) {
            xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

            String beanElement = type.getAnnotation(XmlRootElement.class).name();
            String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

            //create transformer
            Transformer transformer = transformerFactory.newTransformer(xsltSource);
            transformer.setParameter("bean_element", beanElement);
            transformer.setParameter("bean_namespace", beanNamespace);

            //transform
            StringResult result = new StringResult();
            transformer.transform(xmlSource, result);
            FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
            return;
        }
    } catch (IOException e) {
        throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
        throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
}

From source file:eu.domibus.ebms3.receiver.MSHWebservice.java

/**
 * Handles Receipt generation for a incoming message
 *
 * @param request          the incoming message
 * @param legConfiguration processing information of the message
 * @param duplicate        indicates whether or not the message is a duplicate
 * @return the response message to the incoming request message
 * @throws EbMS3Exception if generation of receipt was not successful
 *//*w  w w . j a  v  a  2s  . c  o m*/
private SOAPMessage generateReceipt(SOAPMessage request, LegConfiguration legConfiguration, Boolean duplicate)
        throws EbMS3Exception {
    SOAPMessage responseMessage = null;

    assert legConfiguration != null;

    if (legConfiguration.getReliability() == null) {
        return responseMessage;
    }

    if (ReplyPattern.RESPONSE.equals(legConfiguration.getReliability().getReplyPattern())) {
        MSHWebservice.LOG.debug("Checking reliability for incoming message");
        try {
            responseMessage = this.messageFactory.createMessage();
            Source messageToReceiptTransform = new StreamSource(
                    this.getClass().getClassLoader().getResourceAsStream("./xslt/GenerateAS4Receipt.xsl"));
            Transformer transformer = this.transformerFactory.newTransformer(messageToReceiptTransform);
            Source requestMessage = request.getSOAPPart().getContent();
            transformer.setParameter("messageid", this.messageIdGenerator.generateMessageId());
            transformer.setParameter("timestamp", this.timestampDateFormatter.generateTimestamp());
            transformer.setParameter("nonRepudiation",
                    Boolean.toString(legConfiguration.getReliability().isNonRepudiation()));

            DOMResult domResult = new DOMResult();

            transformer.transform(requestMessage, domResult);
            responseMessage.getSOAPPart().setContent(new DOMSource(domResult.getNode()));

            //                transformer.transform(requestMessage, new DOMResult(responseMessage.getSOAPPart().getEnvelope()));
        } catch (TransformerConfigurationException | SOAPException e) {
            // this cannot happen
            assert false;
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0201,
                    "Could not generate Receipt. Check security header and non-repudiation settings", null, e,
                    MSHRole.RECEIVING);
        }
    }

    return responseMessage;
}

From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method updates an existing Spring bean definition in a XML application context file. Bean definition is
 * identified by its id or bean name./*from  ww  w. jav  a  2  s  .  c  om*/
 * @param project
 * @param id
 * @param jaxbElement
 */
public void updateBeanDefinition(File configFile, Project project, String id, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/update-bean.xsl").getInputStream());
        xsltSource.setSystemId("update-bean");

        List<File> configFiles = new ArrayList<>();
        configFiles.add(configFile);
        configFiles.addAll(getConfigImports(configFile, project));

        LSParser parser = XMLUtils.createLSParser();
        GetSpringBeanFilter getBeanFilter = new GetSpringBeanFilter(id, jaxbElement.getClass());
        parser.setFilter(getBeanFilter);

        for (File file : configFiles) {
            parser.parseURI(file.toURI().toString());
            if (getBeanFilter.getBeanDefinition() != null) {
                xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

                //create transformer
                Transformer transformer = transformerFactory.newTransformer(xsltSource);
                transformer.setParameter("bean_id", id);
                transformer.setParameter("bean_content", getXmlContent(jaxbElement)
                        .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                        .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

                //transform
                StringResult result = new StringResult();
                transformer.transform(xmlSource, result);
                FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
                return;
            }
        }
    } catch (IOException e) {
        throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
        throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
}

From source file:com.consol.citrus.admin.service.spring.SpringBeanService.java

/**
 * Method updates existing Spring bean definitions in a XML application context file. Bean definition is
 * identified by its type defining class.
 *
 * @param project//from www . j  av a  2s  .  co m
 * @param type
 * @param jaxbElement
 */
public void updateBeanDefinitions(File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
        xsltSource = new StreamSource(new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
        xsltSource.setSystemId("update-bean");

        List<File> configFiles = new ArrayList<>();
        configFiles.add(configFile);
        configFiles.addAll(getConfigImports(configFile, project));

        LSParser parser = XMLUtils.createLSParser();
        GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
        parser.setFilter(getBeanFilter);

        for (File file : configFiles) {
            parser.parseURI(file.toURI().toString());
            if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
                xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

                String beanElement = type.getAnnotation(XmlRootElement.class).name();
                String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

                //create transformer
                Transformer transformer = transformerFactory.newTransformer(xsltSource);
                transformer.setParameter("bean_element", beanElement);
                transformer.setParameter("bean_namespace", beanNamespace);
                transformer.setParameter("bean_content", getXmlContent(jaxbElement)
                        .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                        .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

                //transform
                StringResult result = new StringResult();
                transformer.transform(xmlSource, result);
                FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
                return;
            }
        }
    } catch (IOException e) {
        throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
        throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
}

From source file:com.spoledge.audao.generator.GeneratorFlow.java

private void generateSql(ResourceType type, String name) throws IOException, TransformerException {
    Transformer transformer = getTransformer(type);

    if (transformer == null)
        return;/*  www .  j  a  v  a  2  s. c  om*/

    setDbType(transformer);
    transformer.setParameter("db_user", "__USERNAME__");

    transformer.transform(getSource(), output.addResult(name));
}

From source file:com.agilejava.docbkx.maven.AbstractWebhelpMojo.java

/**
 * DOCUMENT ME!/*from  www  . j  a  va  2  s  .c  o m*/
 *
 * @param transformer DOCUMENT ME!
 * @param sourceFilename DOCUMENT ME!
 * @param targetFile DOCUMENT ME!
 */
public void adjustTransformer(Transformer transformer, String sourceFilename, File targetFile) {
    super.adjustTransformer(transformer, sourceFilename, targetFile);

    String rootFilename = "index.html";
    rootFilename = rootFilename.substring(0, rootFilename.lastIndexOf('.'));
    transformer.setParameter("root.filename", rootFilename);
    transformer.setParameter("webhelp.base.dir", targetFile.getParent() + File.separator);
    targetBaseDir = targetFile.getParentFile();
    searchBaseDir = new File(targetBaseDir, "search");
    cleanUpStrings = new ArrayList();
    cleanUpChars = new ArrayList();
    tempDico = new HashMap();
}

From source file:com.seajas.search.attender.service.template.TemplateService.java

/**
 * Create a confirmation template result.
 * //from w  w  w  .j a v  a  2  s.  com
 * @param language
 * @param queryString
 * @param subscriberUUID
 * @param profileUUID
 */
public TemplateResult createConfirmation(final String language, final String queryString,
        final String subscriberUUID, final String profileUUID) throws Exception {
    Template template = templateDAO.findTemplate(TemplateType.Confirmation, language);

    if (template == null) {
        logger.warn("Could not retrieve confirmation template for language " + language
                + " - falling back to the default language " + attenderService.getDefaultApplicationLanguage());

        template = templateDAO.findTemplate(TemplateType.Confirmation,
                attenderService.getDefaultApplicationLanguage());

        if (template == null) {
            logger.error("Could not retrieve fall-back confirmation template for language "
                    + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

            return null;
        }
    }

    try {
        // Plain text

        Transformer textTransformer = getTransformer(template, true);
        StringWriter textWriter = new StringWriter();

        textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        textTransformer.setParameter("subscriberUUID", subscriberUUID);
        textTransformer.setParameter("profileUUID", profileUUID);
        textTransformer.setParameter("queryString", queryString);
        textTransformer.transform(new DOMSource(), new StreamResult(textWriter));

        // HTML

        Transformer htmlTransformer = getTransformer(template, false);
        StringWriter htmlWriter = new StringWriter();

        htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        htmlTransformer.setParameter("subscriberUUID", subscriberUUID);
        htmlTransformer.setParameter("profileUUID", profileUUID);
        htmlTransformer.setParameter("queryString", queryString);
        htmlTransformer.transform(new DOMSource(), new StreamResult(htmlWriter));

        return new TemplateResult(textWriter.toString(), htmlWriter.toString());
    } catch (ScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new Exception(e);
    }
}

From source file:com.spoledge.audao.generator.GeneratorFlow.java

public void generateDaos() throws IOException, TransformerException {
    Transformer transformer = getTransformer(ResourceType.DAO);
    String path = dirName + "dao/";

    for (String tableName : getTableNames()) {
        transformer.setParameter("table_name", tableName);
        transformer.transform(getSource(), output.addResult(file(path, tableName, "Dao")));
    }// w  ww .ja v a2  s.c  o  m
}

From source file:org.ambraproject.admin.service.impl.DocumentManagementServiceImpl.java

/**
 * Generate the xml doc to send to crossref
 * <p/>//  w ww .  j a v a 2s.c o  m
 *
 * @param articleXml - the article xml
 * @param articleId  - the article Id
 * @throws javax.xml.transform.TransformerException
 *          - if there's a problem transforming the article xml
 */
@Override
public void generateCrossrefInfoDoc(Document articleXml, URI articleId) throws TransformerException {
    log.info("Generating crossref info doc for article " + articleId);

    try {
        Transformer t = getTranslet(articleXml);
        t.setParameter("plosDoiUrl", plosDoiUrl);
        t.setParameter("plosEmail", plosEmail);

        File target_xml = new File(ingestedDocumentDirectory, getCrossrefDocFileName(articleId));

        t.transform(new DOMSource(articleXml, articleId.toString()), new StreamResult(target_xml));
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}