Search in sources :

Example 1 with DOMResult

use of javax.xml.transform.dom.DOMResult in project camel by apache.

the class ValidatingProcessor method doProcess.

protected void doProcess(Exchange exchange) throws Exception {
    Schema schema;
    if (isUseSharedSchema()) {
        schema = getSchema();
    } else {
        schema = createSchema();
    }
    Validator validator = schema.newValidator();
    // the underlying input stream, which we need to close to avoid locking files or other resources
    Source source = null;
    InputStream is = null;
    try {
        Result result = null;
        // only convert to input stream if really needed
        if (isInputStreamNeeded(exchange)) {
            is = getContentToValidate(exchange, InputStream.class);
            if (is != null) {
                source = getSource(exchange, is);
            }
        } else {
            Object content = getContentToValidate(exchange);
            if (content != null) {
                source = getSource(exchange, content);
            }
        }
        if (shouldUseHeader()) {
            if (source == null && isFailOnNullHeader()) {
                throw new NoXmlHeaderValidationException(exchange, headerName);
            }
        } else {
            if (source == null && isFailOnNullBody()) {
                throw new NoXmlBodyValidationException(exchange);
            }
        }
        //CAMEL-7036 We don't need to set the result if the source is an instance of StreamSource
        if (source instanceof DOMSource) {
            result = new DOMResult();
        } else if (source instanceof SAXSource) {
            result = new SAXResult();
        } else if (source instanceof StAXSource || source instanceof StreamSource) {
            result = null;
        }
        if (source != null) {
            // create a new errorHandler and set it on the validator
            // must be a local instance to avoid problems with concurrency (to be
            // thread safe)
            ValidatorErrorHandler handler = errorHandler.getClass().newInstance();
            validator.setErrorHandler(handler);
            try {
                LOG.trace("Validating {}", source);
                validator.validate(source, result);
                handler.handleErrors(exchange, schema, result);
            } catch (SAXParseException e) {
                // can be thrown for non well formed XML
                throw new SchemaValidationException(exchange, schema, Collections.singletonList(e), Collections.<SAXParseException>emptyList(), Collections.<SAXParseException>emptyList());
            }
        }
    } finally {
        IOHelper.close(is);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMResult(javax.xml.transform.dom.DOMResult) InputStream(java.io.InputStream) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) StAXSource(javax.xml.transform.stax.StAXSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) SAXSource(javax.xml.transform.sax.SAXSource) StAXSource(javax.xml.transform.stax.StAXSource) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) DOMResult(javax.xml.transform.dom.DOMResult) SAXSource(javax.xml.transform.sax.SAXSource) SAXResult(javax.xml.transform.sax.SAXResult) SAXParseException(org.xml.sax.SAXParseException) Validator(javax.xml.validation.Validator)

Example 2 with DOMResult

use of javax.xml.transform.dom.DOMResult in project camel by apache.

the class XmlConverter method toDOMNodeFromStAX.

@Converter
public Node toDOMNodeFromStAX(StAXSource source) throws ParserConfigurationException, IOException, SAXException, TransformerException {
    DOMResult result = new DOMResult();
    toResult(source, result);
    return result.getNode();
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) Converter(org.apache.camel.Converter)

Example 3 with DOMResult

use of javax.xml.transform.dom.DOMResult 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)

Example 4 with DOMResult

use of javax.xml.transform.dom.DOMResult in project camel by apache.

the class XmlFixture method transform.

protected static Document transform(Document aDocument, String aResourcePath) throws Exception {
    TransformerFactory tf = TransformerFactory.newInstance();
    InputStream in = XmlFixture.class.getResourceAsStream(aResourcePath);
    Source src = new StreamSource(in);
    src.setSystemId(XmlFixture.class.getResource(aResourcePath).toExternalForm());
    Transformer t = tf.newTransformer(src);
    DOMResult result = new DOMResult();
    t.transform(new DOMSource(aDocument), result);
    return (Document) result.getNode();
}
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) StreamSource(javax.xml.transform.stream.StreamSource) Document(org.w3c.dom.Document) DOMSource(javax.xml.transform.dom.DOMSource) InputSource(org.xml.sax.InputSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source)

Example 5 with DOMResult

use of javax.xml.transform.dom.DOMResult in project robovm by robovm.

the class TransformerIdentityImpl method createResultContentHandler.

/**
   * Create a result ContentHandler from a Result object, based
   * on the current OutputProperties.
   *
   * @param outputTarget Where the transform result should go,
   * should not be null.
   *
   * @return A valid ContentHandler that will create the
   * result tree when it is fed SAX events.
   *
   * @throws TransformerException
   */
private void createResultContentHandler(Result outputTarget) throws TransformerException {
    if (outputTarget instanceof SAXResult) {
        SAXResult saxResult = (SAXResult) outputTarget;
        m_resultContentHandler = saxResult.getHandler();
        m_resultLexicalHandler = saxResult.getLexicalHandler();
        if (m_resultContentHandler instanceof Serializer) {
            // Dubious but needed, I think.
            m_serializer = (Serializer) m_resultContentHandler;
        }
    } else if (outputTarget instanceof DOMResult) {
        DOMResult domResult = (DOMResult) outputTarget;
        Node outputNode = domResult.getNode();
        Node nextSibling = domResult.getNextSibling();
        Document doc;
        short type;
        if (null != outputNode) {
            type = outputNode.getNodeType();
            doc = (Node.DOCUMENT_NODE == type) ? (Document) outputNode : outputNode.getOwnerDocument();
        } else {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
                if (m_isSecureProcessing) {
                    try {
                        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (ParserConfigurationException pce) {
                    }
                }
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.newDocument();
            } catch (ParserConfigurationException pce) {
                throw new TransformerException(pce);
            }
            outputNode = doc;
            type = outputNode.getNodeType();
            ((DOMResult) outputTarget).setNode(outputNode);
        }
        DOMBuilder domBuilder = (Node.DOCUMENT_FRAGMENT_NODE == type) ? new DOMBuilder(doc, (DocumentFragment) outputNode) : new DOMBuilder(doc, outputNode);
        if (nextSibling != null)
            domBuilder.setNextSibling(nextSibling);
        m_resultContentHandler = domBuilder;
        m_resultLexicalHandler = domBuilder;
    } else if (outputTarget instanceof StreamResult) {
        StreamResult sresult = (StreamResult) outputTarget;
        try {
            Serializer serializer = SerializerFactory.getSerializer(m_outputFormat.getProperties());
            m_serializer = serializer;
            if (null != sresult.getWriter())
                serializer.setWriter(sresult.getWriter());
            else if (null != sresult.getOutputStream())
                serializer.setOutputStream(sresult.getOutputStream());
            else if (null != sresult.getSystemId()) {
                String fileURL = sresult.getSystemId();
                if (fileURL.startsWith("file:///")) {
                    if (fileURL.substring(8).indexOf(":") > 0) {
                        fileURL = fileURL.substring(8);
                    } else {
                        fileURL = fileURL.substring(7);
                    }
                } else if (fileURL.startsWith("file:/")) {
                    if (fileURL.substring(6).indexOf(":") > 0) {
                        fileURL = fileURL.substring(6);
                    } else {
                        fileURL = fileURL.substring(5);
                    }
                }
                m_outputStream = new java.io.FileOutputStream(fileURL);
                serializer.setOutputStream(m_outputStream);
            } else
                //"No output specified!");
                throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_OUTPUT_SPECIFIED, null));
            m_resultContentHandler = serializer.asContentHandler();
        } catch (IOException ioe) {
            throw new TransformerException(ioe);
        }
    } else {
        //"Can't transform to a Result of type "
        throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_TO_RESULT_TYPE, new Object[] { outputTarget.getClass().getName() }));
    // + outputTarget.getClass().getName()
    // + "!");
    }
    if (m_resultContentHandler instanceof DTDHandler)
        m_resultDTDHandler = (DTDHandler) m_resultContentHandler;
    if (m_resultContentHandler instanceof DeclHandler)
        m_resultDeclHandler = (DeclHandler) m_resultContentHandler;
    if (m_resultContentHandler instanceof LexicalHandler)
        m_resultLexicalHandler = (LexicalHandler) m_resultContentHandler;
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) StreamResult(javax.xml.transform.stream.StreamResult) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) DOMBuilder(org.apache.xml.utils.DOMBuilder) DeclHandler(org.xml.sax.ext.DeclHandler) SAXResult(javax.xml.transform.sax.SAXResult) DocumentBuilder(javax.xml.parsers.DocumentBuilder) LexicalHandler(org.xml.sax.ext.LexicalHandler) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) DTDHandler(org.xml.sax.DTDHandler) TransformerException(javax.xml.transform.TransformerException) Serializer(org.apache.xml.serializer.Serializer)

Aggregations

DOMResult (javax.xml.transform.dom.DOMResult)61 Document (org.w3c.dom.Document)33 DOMSource (javax.xml.transform.dom.DOMSource)24 Transformer (javax.xml.transform.Transformer)20 DocumentBuilder (javax.xml.parsers.DocumentBuilder)17 TransformerException (javax.xml.transform.TransformerException)14 IOException (java.io.IOException)13 InputSource (org.xml.sax.InputSource)13 StreamSource (javax.xml.transform.stream.StreamSource)12 StringReader (java.io.StringReader)11 SAXResult (javax.xml.transform.sax.SAXResult)10 Element (org.w3c.dom.Element)10 Node (org.w3c.dom.Node)10 SAXSource (javax.xml.transform.sax.SAXSource)9 StreamResult (javax.xml.transform.stream.StreamResult)9 Test (org.junit.Test)9 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)8 Source (javax.xml.transform.Source)8 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)7 InputStream (java.io.InputStream)6