Search in sources :

Example 1 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project camel by apache.

the class FopProducer method transform.

private OutputStream transform(FOUserAgent userAgent, String outputFormat, Source src) throws FOPException, TransformerException {
    OutputStream out = new ByteArrayOutputStream();
    Fop fop = fopFactory.newFop(outputFormat, userAgent, out);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    Result res = new SAXResult(fop.getDefaultHandler());
    transformer.transform(src, res);
    return out;
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) SAXResult(javax.xml.transform.sax.SAXResult) Fop(org.apache.fop.apps.Fop) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult)

Example 2 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project camel by apache.

the class XsltEndpoint method doStart.

@Override
protected void doStart() throws Exception {
    super.doStart();
    final CamelContext ctx = getCamelContext();
    final ClassResolver resolver = ctx.getClassResolver();
    final Injector injector = ctx.getInjector();
    LOG.debug("{} using schema resource: {}", this, resourceUri);
    this.xslt = injector.newInstance(XsltBuilder.class);
    if (converter != null) {
        xslt.setConverter(converter);
    }
    boolean useSaxon = false;
    if (transformerFactoryClass == null && (saxon || saxonExtensionFunctions != null)) {
        useSaxon = true;
        transformerFactoryClass = SAXON_TRANSFORMER_FACTORY_CLASS_NAME;
    }
    TransformerFactory factory = transformerFactory;
    if (factory == null && transformerFactoryClass != null) {
        // provide the class loader of this component to work in OSGi environments
        Class<TransformerFactory> factoryClass = resolver.resolveMandatoryClass(transformerFactoryClass, TransformerFactory.class, XsltComponent.class.getClassLoader());
        LOG.debug("Using TransformerFactoryClass {}", factoryClass);
        factory = injector.newInstance(factoryClass);
        if (useSaxon) {
            XsltHelper.registerSaxonConfiguration(ctx, factoryClass, factory, saxonConfiguration);
            XsltHelper.registerSaxonConfigurationProperties(ctx, factoryClass, factory, saxonConfigurationProperties);
            XsltHelper.registerSaxonExtensionFunctions(ctx, factoryClass, factory, saxonExtensionFunctions);
        }
    }
    if (factory != null) {
        LOG.debug("Using TransformerFactory {}", factory);
        xslt.getConverter().setTransformerFactory(factory);
    }
    if (resultHandlerFactory != null) {
        xslt.setResultHandlerFactory(resultHandlerFactory);
    }
    if (errorListener != null) {
        xslt.errorListener(errorListener);
    }
    xslt.setFailOnNullBody(failOnNullBody);
    xslt.transformerCacheSize(transformerCacheSize);
    xslt.setUriResolver(uriResolver);
    xslt.setEntityResolver(entityResolver);
    xslt.setAllowStAX(allowStAX);
    xslt.setDeleteOutputFile(deleteOutputFile);
    configureOutput(xslt, output.name());
    // any additional transformer parameters then make a copy to avoid side-effects
    if (parameters != null) {
        Map<String, Object> copy = new HashMap<String, Object>(parameters);
        xslt.setParameters(copy);
    }
    // must load resource first which sets a template and do a stylesheet compilation to catch errors early
    loadResource(resourceUri);
    // the processor is the xslt builder
    setProcessor(xslt);
}
Also used : CamelContext(org.apache.camel.CamelContext) TransformerFactory(javax.xml.transform.TransformerFactory) HashMap(java.util.HashMap) Injector(org.apache.camel.spi.Injector) XsltBuilder(org.apache.camel.builder.xml.XsltBuilder) ClassResolver(org.apache.camel.spi.ClassResolver)

Example 3 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project camel by apache.

the class XmlConverter method createTransformerFactory.

public TransformerFactory createTransformerFactory() {
    TransformerFactory factory;
    TransformerFactoryConfigurationError cause;
    try {
        factory = TransformerFactory.newInstance();
    } catch (TransformerFactoryConfigurationError e) {
        cause = e;
        // try fallback from the JDK
        try {
            LOG.debug("Cannot create/load TransformerFactory due: {}. Will attempt to use JDK fallback TransformerFactory: {}", e.getMessage(), JDK_FALLBACK_TRANSFORMER_FACTORY);
            factory = TransformerFactory.newInstance(JDK_FALLBACK_TRANSFORMER_FACTORY, null);
        } catch (Throwable t) {
            // okay we cannot load fallback then throw original exception
            throw cause;
        }
    }
    LOG.debug("Created TransformerFactory: {}", factory);
    // Enable the Security feature by default
    try {
        factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (TransformerConfigurationException e) {
        LOG.warn("TransformerFactory doesn't support the feature {} with value {}, due to {}.", new Object[] { javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, "true", e });
    }
    factory.setErrorListener(new XmlErrorListener());
    configureSaxonTransformerFactory(factory);
    return factory;
}
Also used : TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) TransformerFactory(javax.xml.transform.TransformerFactory) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException)

Example 4 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project camel by apache.

the class StAX2SAXSourceTest method testDefaultPrefixInRootElementWithCopyTransformer.

public void testDefaultPrefixInRootElementWithCopyTransformer() throws Exception {
    TransformerFactory trf = TransformerFactory.newInstance();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLStreamReader reader = context.getTypeConverter().mandatoryConvertTo(XMLStreamReader.class, new StringReader(TEST_XML));
    // ensure UTF-8 encoding
    Exchange exchange = new DefaultExchange(context);
    exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.toString());
    XMLStreamWriter writer = context.getTypeConverter().mandatoryConvertTo(XMLStreamWriter.class, exchange, baos);
    StAX2SAXSource staxSource = new StAX2SAXSource(reader);
    StreamSource templateSource = new StreamSource(getClass().getResourceAsStream("/xslt/common/copy.xsl"));
    Transformer transformer = trf.newTransformer(templateSource);
    log.info("Used transformer: {}", transformer.getClass().getName());
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(staxSource, new StreamResult(baos));
    writer.flush();
    baos.flush();
    assertThat(new String(baos.toByteArray()), equalTo(TEST_XML));
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) TransformerFactory(javax.xml.transform.TransformerFactory) XMLStreamReader(javax.xml.stream.XMLStreamReader) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) StreamSource(javax.xml.transform.stream.StreamSource) StringReader(java.io.StringReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 5 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project camel by apache.

the class CacheBasedXPathReplacer method process.

public void process(Exchange exchange) throws Exception {
    String cacheKey = key.evaluate(exchange, String.class);
    if (isValid(cacheManager, cacheName, cacheKey)) {
        Ehcache cache = cacheManager.getCache(cacheName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Replacing XPath value {} in Message with value stored against key {} in CacheName {}", new Object[] { xpath, cacheKey, cacheName });
        }
        exchange.getIn().setHeader(CacheConstants.CACHE_KEY, cacheKey);
        Object body = exchange.getIn().getBody();
        InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, body);
        Document document;
        try {
            document = exchange.getContext().getTypeConverter().convertTo(Document.class, exchange, is);
        } finally {
            IOHelper.close(is, "is", LOG);
        }
        InputStream cis = exchange.getContext().getTypeConverter().convertTo(InputStream.class, cache.get(cacheKey).getObjectValue());
        try {
            Document cacheValueDocument = exchange.getContext().getTypeConverter().convertTo(Document.class, exchange, cis);
            // Create/setup the Transformer
            XmlConverter xmlConverter = new XmlConverter();
            String xslString = IOConverter.toString(new File("./src/main/resources/xpathreplacer.xsl"), exchange);
            xslString = xslString.replace("##match_token##", xpath);
            Source xslSource = xmlConverter.toStreamSource(new StringReader(xslString));
            TransformerFactory transformerFactory = xmlConverter.createTransformerFactory();
            Transformer transformer = transformerFactory.newTransformer(xslSource);
            DOMSource source = xmlConverter.toDOMSource(document);
            DOMResult result = new DOMResult();
            transformer.setParameter("cacheValue", cacheValueDocument);
            transformer.transform(source, result);
            // DOMSource can be converted to byte[] by camel type converter mechanism
            DOMSource dom = new DOMSource(result.getNode());
            exchange.getIn().setBody(dom, byte[].class);
        } finally {
            IOHelper.close(cis, "cis", LOG);
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) DOMResult(javax.xml.transform.dom.DOMResult) InputStream(java.io.InputStream) Document(org.w3c.dom.Document) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) XmlConverter(org.apache.camel.converter.jaxp.XmlConverter) StringReader(java.io.StringReader) Ehcache(net.sf.ehcache.Ehcache) File(java.io.File)

Aggregations

TransformerFactory (javax.xml.transform.TransformerFactory)188 Transformer (javax.xml.transform.Transformer)158 StreamResult (javax.xml.transform.stream.StreamResult)137 DOMSource (javax.xml.transform.dom.DOMSource)113 TransformerException (javax.xml.transform.TransformerException)63 StreamSource (javax.xml.transform.stream.StreamSource)60 StringWriter (java.io.StringWriter)58 Document (org.w3c.dom.Document)53 IOException (java.io.IOException)42 Source (javax.xml.transform.Source)41 DocumentBuilder (javax.xml.parsers.DocumentBuilder)37 File (java.io.File)36 Element (org.w3c.dom.Element)31 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)29 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)27 Result (javax.xml.transform.Result)24 SAXException (org.xml.sax.SAXException)24 StringReader (java.io.StringReader)23 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)23 ByteArrayOutputStream (java.io.ByteArrayOutputStream)20