Search in sources :

Example 1 with Document

use of org.w3c.dom.Document 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 Document

use of org.w3c.dom.Document 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 Document

use of org.w3c.dom.Document 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 Document

use of org.w3c.dom.Document 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)

Example 5 with Document

use of org.w3c.dom.Document in project camel by apache.

the class RawMessageWSDLGetInterceptor method handleMessage.

public void handleMessage(Message message) throws Fault {
    String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
    String query = (String) message.get(Message.QUERY_STRING);
    if (!"GET".equals(method) || StringUtils.isEmpty(query)) {
        return;
    }
    String baseUri = (String) message.get(Message.REQUEST_URL);
    String ctx = (String) message.get(Message.PATH_INFO);
    Map<String, String> map = UrlUtils.parseQueryString(query);
    if (isRecognizedQuery(map, baseUri, ctx, message.getExchange().getEndpoint().getEndpointInfo())) {
        Document doc = getDocument(message, baseUri, map, ctx);
        Endpoint e = message.getExchange().get(Endpoint.class);
        Message mout = new MessageImpl();
        mout.setExchange(message.getExchange());
        mout = e.getBinding().createMessage(mout);
        mout.setInterceptorChain(OutgoingChainInterceptor.getOutInterceptorChain(message.getExchange()));
        message.getExchange().setOutMessage(mout);
        mout.put(DOCUMENT_HOLDER, doc);
        Iterator<Interceptor<? extends Message>> iterator = mout.getInterceptorChain().iterator();
        while (iterator.hasNext()) {
            Interceptor<? extends Message> inInterceptor = iterator.next();
            if (inInterceptor instanceof AbstractPhaseInterceptor) {
                AbstractPhaseInterceptor<?> interceptor = (AbstractPhaseInterceptor<?>) inInterceptor;
                if (interceptor.getPhase().equals(Phase.PREPARE_SEND) || interceptor.getPhase().equals(Phase.PRE_STREAM)) {
                    // just make sure we keep the right interceptors
                    continue;
                }
            }
            mout.getInterceptorChain().remove(inInterceptor);
        }
        // notice this is being added after the purge above, don't swap the order!
        mout.getInterceptorChain().add(RawMessageWSDLGetOutInterceptor.INSTANCE);
        // skip the service executor and goto the end of the chain.
        message.getInterceptorChain().doInterceptStartingAt(message, OutgoingChainInterceptor.class.getName());
    }
}
Also used : Endpoint(org.apache.cxf.endpoint.Endpoint) Message(org.apache.cxf.message.Message) OutgoingChainInterceptor(org.apache.cxf.interceptor.OutgoingChainInterceptor) AbstractPhaseInterceptor(org.apache.cxf.phase.AbstractPhaseInterceptor) Document(org.w3c.dom.Document) MessageImpl(org.apache.cxf.message.MessageImpl) Interceptor(org.apache.cxf.interceptor.Interceptor) AbstractPhaseInterceptor(org.apache.cxf.phase.AbstractPhaseInterceptor) EndpointSelectionInterceptor(org.apache.cxf.binding.soap.interceptor.EndpointSelectionInterceptor) OutgoingChainInterceptor(org.apache.cxf.interceptor.OutgoingChainInterceptor)

Aggregations

Document (org.w3c.dom.Document)2446 Element (org.w3c.dom.Element)990 DocumentBuilder (javax.xml.parsers.DocumentBuilder)719 NodeList (org.w3c.dom.NodeList)648 Node (org.w3c.dom.Node)545 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)528 IOException (java.io.IOException)425 SAXException (org.xml.sax.SAXException)301 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)299 InputSource (org.xml.sax.InputSource)250 Test (org.junit.Test)233 File (java.io.File)190 StringReader (java.io.StringReader)182 ArrayList (java.util.ArrayList)174 InputStream (java.io.InputStream)167 DOMSource (javax.xml.transform.dom.DOMSource)161 ByteArrayInputStream (java.io.ByteArrayInputStream)154 Attr (org.w3c.dom.Attr)134 DOMException (org.w3c.dom.DOMException)129 XPath (javax.xml.xpath.XPath)107