Search in sources :

Example 1 with DOMSource

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

the class CMSenderOneMessageImpl method createXml.

private String createXml(final CMMessage message) {
    try {
        final ByteArrayOutputStream xml = new ByteArrayOutputStream();
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        // Get the DocumentBuilder
        final DocumentBuilder docBuilder = factory.newDocumentBuilder();
        // Create blank DOM Document
        final DOMImplementation impl = docBuilder.getDOMImplementation();
        final Document doc = impl.createDocument(null, "MESSAGES", null);
        // ROOT Element es MESSAGES
        final Element root = doc.getDocumentElement();
        // AUTHENTICATION element
        final Element authenticationElement = doc.createElement("AUTHENTICATION");
        final Element productTokenElement = doc.createElement("PRODUCTTOKEN");
        authenticationElement.appendChild(productTokenElement);
        final Text productTokenValue = doc.createTextNode("" + productToken);
        productTokenElement.appendChild(productTokenValue);
        root.appendChild(authenticationElement);
        // MSG Element
        final Element msgElement = doc.createElement("MSG");
        root.appendChild(msgElement);
        // <FROM>VALUE</FROM>
        final Element fromElement = doc.createElement("FROM");
        fromElement.appendChild(doc.createTextNode(message.getSender()));
        msgElement.appendChild(fromElement);
        // <BODY>VALUE</BODY>
        final Element bodyElement = doc.createElement("BODY");
        bodyElement.appendChild(doc.createTextNode(message.getMessage()));
        msgElement.appendChild(bodyElement);
        // <TO>VALUE</TO>
        final Element toElement = doc.createElement("TO");
        toElement.appendChild(doc.createTextNode(message.getPhoneNumber()));
        msgElement.appendChild(toElement);
        // false
        if (message.isUnicode()) {
            final Element dcsElement = doc.createElement("DCS");
            dcsElement.appendChild(doc.createTextNode("8"));
            msgElement.appendChild(dcsElement);
        }
        // <REFERENCE>VALUE</REFERENCE> -Alfanum
        final String id = message.getIdAsString();
        if (id != null && !id.isEmpty()) {
            final Element refElement = doc.createElement("REFERENCE");
            refElement.appendChild(doc.createTextNode("" + message.getIdAsString()));
            msgElement.appendChild(refElement);
        }
        // <MAXIMUMNUMBEROFMESSAGEPARTS>8</MAXIMUMNUMBEROFMESSAGEPARTS>
        if (message.isMultipart()) {
            final Element minMessagePartsElement = doc.createElement("MINIMUMNUMBEROFMESSAGEPARTS");
            minMessagePartsElement.appendChild(doc.createTextNode("1"));
            msgElement.appendChild(minMessagePartsElement);
            final Element maxMessagePartsElement = doc.createElement("MAXIMUMNUMBEROFMESSAGEPARTS");
            maxMessagePartsElement.appendChild(doc.createTextNode(Integer.toString(message.getMultiparts())));
            msgElement.appendChild(maxMessagePartsElement);
        }
        // Creatate XML as String
        final Transformer aTransformer = TransformerFactory.newInstance().newTransformer();
        aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        final Source src = new DOMSource(doc);
        final Result dest = new StreamResult(xml);
        aTransformer.transform(src, dest);
        return xml.toString();
    } catch (final TransformerException e) {
        throw new XMLConstructionException(String.format("Cant serialize CMMessage %s", message), e);
    } catch (final ParserConfigurationException e) {
        throw new XMLConstructionException(String.format("Cant serialize CMMessage %s", message), e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) DOMImplementation(org.w3c.dom.DOMImplementation) Text(org.w3c.dom.Text) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) XMLConstructionException(org.apache.camel.component.cm.exceptions.XMLConstructionException) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 2 with DOMSource

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

the class CxfPayloadConverter method convertTo.

@SuppressWarnings("unchecked")
@FallbackConverter
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
    // CxfPayloads from other types
    if (type.isAssignableFrom(CxfPayload.class)) {
        try {
            if (!value.getClass().isArray()) {
                Source src = null;
                // directly
                if (value instanceof InputStream) {
                    src = new StreamSource((InputStream) value);
                } else if (value instanceof Reader) {
                    src = new StreamSource((Reader) value);
                } else if (value instanceof String) {
                    src = new StreamSource(new StringReader((String) value));
                } else if (value instanceof Node) {
                    src = new DOMSource((Node) value);
                } else if (value instanceof Source) {
                    src = (Source) value;
                }
                if (src == null) {
                    // assuming staxsource is preferred, otherwise use the
                    // one preferred
                    TypeConverter tc = registry.lookup(javax.xml.transform.stax.StAXSource.class, value.getClass());
                    if (tc == null) {
                        tc = registry.lookup(Source.class, value.getClass());
                    }
                    if (tc != null) {
                        src = tc.convertTo(Source.class, exchange, value);
                    }
                }
                if (src != null) {
                    return (T) sourceToCxfPayload(src, exchange);
                }
            }
            TypeConverter tc = registry.lookup(NodeList.class, value.getClass());
            if (tc != null) {
                NodeList nodeList = tc.convertTo(NodeList.class, exchange, value);
                return (T) nodeListToCxfPayload(nodeList, exchange);
            }
            tc = registry.lookup(Document.class, value.getClass());
            if (tc != null) {
                Document document = tc.convertTo(Document.class, exchange, value);
                return (T) documentToCxfPayload(document, exchange);
            }
            // maybe we can convert via an InputStream
            CxfPayload<?> p;
            p = convertVia(InputStream.class, exchange, value, registry);
            if (p != null) {
                return (T) p;
            }
            // String is the converter of last resort
            p = convertVia(String.class, exchange, value, registry);
            if (p != null) {
                return (T) p;
            }
        } catch (RuntimeCamelException e) {
        // the internal conversion to XML can throw an exception if the content is not XML
        // ignore this and return Void.TYPE to indicate that we cannot convert this
        }
        // no we could not do it currently
        return (T) Void.TYPE;
    }
    // Convert a CxfPayload into something else
    if (CxfPayload.class.isAssignableFrom(value.getClass())) {
        CxfPayload<?> payload = (CxfPayload<?>) value;
        int size = payload.getBodySources().size();
        if (size == 1) {
            if (type.isAssignableFrom(Document.class)) {
                Source s = payload.getBodySources().get(0);
                Document d;
                try {
                    d = StaxUtils.read(s);
                } catch (XMLStreamException e) {
                    throw new RuntimeException(e);
                }
                return type.cast(d);
            }
            // CAMEL-8410 Just make sure we get the Source object directly from the payload body source
            Source s = payload.getBodySources().get(0);
            if (type.isInstance(s)) {
                return type.cast(s);
            }
            TypeConverter tc = registry.lookup(type, XMLStreamReader.class);
            if (tc != null && (s instanceof StaxSource || s instanceof StAXSource)) {
                XMLStreamReader r = (s instanceof StAXSource) ? ((StAXSource) s).getXMLStreamReader() : ((StaxSource) s).getXMLStreamReader();
                if (payload.getNsMap() != null) {
                    r = new DelegatingXMLStreamReader(r, payload.getNsMap());
                }
                return tc.convertTo(type, exchange, r);
            }
            tc = registry.lookup(type, Source.class);
            if (tc != null) {
                XMLStreamReader r = null;
                if (payload.getNsMap() != null) {
                    if (s instanceof StaxSource) {
                        r = ((StaxSource) s).getXMLStreamReader();
                    } else if (s instanceof StAXSource) {
                        r = ((StAXSource) s).getXMLStreamReader();
                    }
                    if (r != null) {
                        s = new StAXSource(new DelegatingXMLStreamReader(r, payload.getNsMap()));
                    }
                }
                return tc.convertTo(type, exchange, s);
            }
        }
        TypeConverter tc = registry.lookup(type, NodeList.class);
        if (tc != null) {
            Object result = tc.convertTo(type, exchange, cxfPayloadToNodeList((CxfPayload<?>) value, exchange));
            if (result == null) {
                // no we could not do it currently, and we just abort the convert here
                return (T) Void.TYPE;
            } else {
                return (T) result;
            }
        }
        // we cannot convert a node list, so we try the first item from the
        // node list
        tc = registry.lookup(type, Node.class);
        if (tc != null) {
            NodeList nodeList = cxfPayloadToNodeList((CxfPayload<?>) value, exchange);
            if (nodeList.getLength() > 0) {
                return tc.convertTo(type, exchange, nodeList.item(0));
            } else {
                // no we could not do it currently
                return (T) Void.TYPE;
            }
        } else {
            if (size == 0) {
                // empty size so we cannot convert
                return (T) Void.TYPE;
            }
        }
    }
    return null;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) CxfPayload(org.apache.camel.component.cxf.CxfPayload) Node(org.w3c.dom.Node) XMLStreamReader(javax.xml.stream.XMLStreamReader) Reader(java.io.Reader) StringReader(java.io.StringReader) Document(org.w3c.dom.Document) DOMSource(javax.xml.transform.dom.DOMSource) StaxSource(org.apache.cxf.staxutils.StaxSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) StAXSource(javax.xml.transform.stax.StAXSource) StringReader(java.io.StringReader) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) NodeList(org.w3c.dom.NodeList) StAXSource(javax.xml.transform.stax.StAXSource) TypeConverter(org.apache.camel.TypeConverter) XMLStreamException(javax.xml.stream.XMLStreamException) StaxSource(org.apache.cxf.staxutils.StaxSource) RuntimeCamelException(org.apache.camel.RuntimeCamelException) FallbackConverter(org.apache.camel.FallbackConverter)

Example 3 with DOMSource

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

the class DefaultCxfBinding method getPayloadBodyElements.

protected static List<Source> getPayloadBodyElements(Message message, Map<String, String> nsMap) {
    // take the namespace attribute from soap envelop
    Map<String, String> bodyNC = CastUtils.cast((Map<?, ?>) message.get("soap.body.ns.context"));
    if (bodyNC != null) {
        // if there is no Node and the addNamespaceContext option is enabled, this map is available
        nsMap.putAll(bodyNC);
    } else {
        Document soapEnv = (Document) message.getContent(Node.class);
        if (soapEnv != null) {
            NamedNodeMap attrs = soapEnv.getFirstChild().getAttributes();
            for (int i = 0; i < attrs.getLength(); i++) {
                Node node = attrs.item(i);
                if (!node.getNodeValue().equals(Soap11.SOAP_NAMESPACE) && !node.getNodeValue().equals(Soap12.SOAP_NAMESPACE)) {
                    nsMap.put(node.getLocalName(), node.getNodeValue());
                }
            }
        }
    }
    MessageContentsList inObjects = MessageContentsList.getContentsList(message);
    if (inObjects == null) {
        return new ArrayList<Source>(0);
    }
    org.apache.cxf.message.Exchange exchange = message.getExchange();
    BindingOperationInfo boi = exchange.getBindingOperationInfo();
    OperationInfo op = boi.getOperationInfo();
    if (boi.isUnwrapped()) {
        op = boi.getWrappedOperation().getOperationInfo();
    }
    List<MessagePartInfo> partInfos = null;
    boolean client = Boolean.TRUE.equals(message.get(Message.REQUESTOR_ROLE));
    if (client) {
        // it is a response
        partInfos = op.getOutput().getMessageParts();
    } else {
        // it is a request
        partInfos = op.getInput().getMessageParts();
    }
    List<Source> answer = new ArrayList<Source>();
    for (MessagePartInfo partInfo : partInfos) {
        if (!inObjects.hasValue(partInfo)) {
            continue;
        }
        Object part = inObjects.get(partInfo);
        if (part instanceof Holder) {
            part = ((Holder<?>) part).value;
        }
        if (part instanceof Source) {
            Element element = null;
            if (part instanceof DOMSource) {
                element = getFirstElement(((DOMSource) part).getNode());
            }
            if (element != null) {
                addNamespace(element, nsMap);
                answer.add(new DOMSource(element));
            } else {
                answer.add((Source) part);
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Extract body element {}", element == null ? "null" : getXMLString(element));
            }
        } else if (part instanceof Element) {
            addNamespace((Element) part, nsMap);
            answer.add(new DOMSource((Element) part));
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Unhandled part type '{}'", part.getClass());
            }
        }
    }
    return answer;
}
Also used : OperationInfo(org.apache.cxf.service.model.OperationInfo) BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) DOMSource(javax.xml.transform.dom.DOMSource) NamedNodeMap(org.w3c.dom.NamedNodeMap) MessageContentsList(org.apache.cxf.message.MessageContentsList) Node(org.w3c.dom.Node) Holder(javax.xml.ws.Holder) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) MessagePartInfo(org.apache.cxf.service.model.MessagePartInfo) Endpoint(org.apache.cxf.endpoint.Endpoint) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source)

Example 4 with DOMSource

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

the class CxfMessageHelperTest method testGetCxfInMessage.

// setup the default context for testing
@Test
public void testGetCxfInMessage() throws Exception {
    HeaderFilterStrategy headerFilterStrategy = new CxfHeaderFilterStrategy();
    org.apache.camel.Exchange exchange = new DefaultExchange(context);
    // String
    exchange.getIn().setBody("hello world");
    org.apache.cxf.message.Message message = CxfMessageHelper.getCxfInMessage(headerFilterStrategy, exchange, false);
    // test message
    InputStream is = message.getContent(InputStream.class);
    assertNotNull("The input stream should not be null", is);
    assertEquals("Don't get the right message", toString(is), "hello world");
    // DOMSource
    URL request = this.getClass().getResource("RequestBody.xml");
    File requestFile = new File(request.toURI());
    FileInputStream inputStream = new FileInputStream(requestFile);
    XMLStreamReader xmlReader = StaxUtils.createXMLStreamReader(inputStream);
    DOMSource source = new DOMSource(StaxUtils.read(xmlReader));
    exchange.getIn().setBody(source);
    message = CxfMessageHelper.getCxfInMessage(headerFilterStrategy, exchange, false);
    is = message.getContent(InputStream.class);
    assertNotNull("The input stream should not be null", is);
    assertEquals("Don't get the right message", toString(is), REQUEST_STRING);
    // File
    exchange.getIn().setBody(requestFile);
    message = CxfMessageHelper.getCxfInMessage(headerFilterStrategy, exchange, false);
    is = message.getContent(InputStream.class);
    assertNotNull("The input stream should not be null", is);
    assertEquals("Don't get the right message", toString(is), REQUEST_STRING);
    // transport header's case insensitiveness
    // String
    exchange.getIn().setBody("hello world");
    exchange.getIn().setHeader("soapAction", "urn:hello:world");
    message = CxfMessageHelper.getCxfInMessage(headerFilterStrategy, exchange, false);
    // test message
    Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    // verify there is no duplicate
    assertNotNull("The headers must be present", headers);
    assertTrue("There must be one header entry", headers.size() == 1);
    // verify the soapaction can be retrieved in case-insensitive ways
    verifyHeader(headers, "soapaction", "urn:hello:world");
    verifyHeader(headers, "SoapAction", "urn:hello:world");
    verifyHeader(headers, "SOAPAction", "urn:hello:world");
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) CxfHeaderFilterStrategy(org.apache.camel.component.cxf.common.header.CxfHeaderFilterStrategy) Message(org.apache.cxf.message.Message) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CxfHeaderFilterStrategy(org.apache.camel.component.cxf.common.header.CxfHeaderFilterStrategy) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) URL(java.net.URL) FileInputStream(java.io.FileInputStream) List(java.util.List) File(java.io.File) Test(org.junit.Test)

Example 5 with DOMSource

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

the class DataInInterceptor method handleMessage.

public void handleMessage(Message message) throws Fault {
    DepthXMLStreamReader xmlReader = getXMLStreamReader(message);
    try {
        // put the payload source as a document
        Document doc = StaxUtils.read(xmlReader);
        message.setContent(Source.class, new DOMSource(doc));
    } catch (XMLStreamException e) {
        throw new Fault(new org.apache.cxf.common.i18n.Message("XMLSTREAM_EXCEPTION", JUL_LOG), e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamException(javax.xml.stream.XMLStreamException) Message(org.apache.cxf.message.Message) Fault(org.apache.cxf.interceptor.Fault) DepthXMLStreamReader(org.apache.cxf.staxutils.DepthXMLStreamReader) Document(org.w3c.dom.Document)

Aggregations

DOMSource (javax.xml.transform.dom.DOMSource)392 StreamResult (javax.xml.transform.stream.StreamResult)231 Transformer (javax.xml.transform.Transformer)204 Document (org.w3c.dom.Document)161 TransformerFactory (javax.xml.transform.TransformerFactory)112 TransformerException (javax.xml.transform.TransformerException)107 DocumentBuilder (javax.xml.parsers.DocumentBuilder)102 StringWriter (java.io.StringWriter)97 IOException (java.io.IOException)93 Element (org.w3c.dom.Element)81 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)77 Source (javax.xml.transform.Source)67 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)62 SAXException (org.xml.sax.SAXException)56 File (java.io.File)55 InputSource (org.xml.sax.InputSource)50 StreamSource (javax.xml.transform.stream.StreamSource)47 Node (org.w3c.dom.Node)45 InputStream (java.io.InputStream)35 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)35