KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > components > saaj > SaajMarshaler


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.components.saaj;
18
19 import java.io.ByteArrayOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.Iterator JavaDoc;
22
23 import javax.activation.DataHandler JavaDoc;
24 import javax.jbi.messaging.MessagingException;
25 import javax.jbi.messaging.NormalizedMessage;
26 import javax.xml.XMLConstants JavaDoc;
27 import javax.xml.parsers.ParserConfigurationException JavaDoc;
28 import javax.xml.soap.AttachmentPart JavaDoc;
29 import javax.xml.soap.MessageFactory JavaDoc;
30 import javax.xml.soap.MimeHeader JavaDoc;
31 import javax.xml.soap.SOAPBody JavaDoc;
32 import javax.xml.soap.SOAPElement JavaDoc;
33 import javax.xml.soap.SOAPEnvelope JavaDoc;
34 import javax.xml.soap.SOAPException JavaDoc;
35 import javax.xml.soap.SOAPMessage JavaDoc;
36 import javax.xml.soap.SOAPPart JavaDoc;
37 import javax.xml.transform.TransformerException JavaDoc;
38 import javax.xml.transform.dom.DOMSource JavaDoc;
39
40 import org.apache.commons.logging.Log;
41 import org.apache.commons.logging.LogFactory;
42 import org.apache.servicemix.jbi.jaxp.SourceTransformer;
43 import org.w3c.dom.Attr JavaDoc;
44 import org.w3c.dom.Document JavaDoc;
45 import org.w3c.dom.NamedNodeMap JavaDoc;
46 import org.xml.sax.SAXException JavaDoc;
47
48 /**
49  * @version $Revision: 431309 $
50  */

51 public class SaajMarshaler {
52
53     private static final transient Log log = LogFactory.getLog(SaajMarshaler.class);
54
55     protected SourceTransformer transformer = new SourceTransformer();
56     private MessageFactory JavaDoc messageFactory;
57
58     public void toNMS(NormalizedMessage normalizedMessage, SOAPMessage JavaDoc soapMessage) throws MessagingException, SOAPException JavaDoc {
59
60         if (log.isDebugEnabled()) {
61             try {
62                 ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
63                 soapMessage.writeTo(buffer);
64                 log.debug(new String JavaDoc(buffer.toByteArray()));
65             } catch (Exception JavaDoc e) { }
66         }
67         
68         addNmsProperties(normalizedMessage, soapMessage);
69
70         SOAPPart JavaDoc soapPart = soapMessage.getSOAPPart();
71         SOAPBody JavaDoc soapBody = soapPart.getEnvelope().getBody();
72         SOAPElement JavaDoc elem = null;
73         for (Iterator JavaDoc it = soapBody.getChildElements(); it.hasNext();) {
74             Object JavaDoc child = it.next();
75             if (child instanceof SOAPElement JavaDoc) {
76                 elem = (SOAPElement JavaDoc) child;
77                 break;
78             }
79         }
80         if (elem == null) {
81             throw new IllegalStateException JavaDoc("Could not find any element in soap body");
82         }
83         
84         for (SOAPElement JavaDoc parent = elem.getParentElement(); parent != null; parent = parent.getParentElement()) {
85             // The following code works with sun saaj implementation
86
NamedNodeMap JavaDoc attributes = parent.getAttributes();
87             if (attributes != null) {
88                 for (int i = 0; i < attributes.getLength(); i++) {
89                     Attr JavaDoc att = (Attr JavaDoc) parent.getAttributes().item(i);
90                     if (att.getName().startsWith(XMLConstants.XMLNS_ATTRIBUTE + ":")
91                             && elem.getAttributeNodeNS(att.getNamespaceURI(), att.getLocalName()) == null) {
92                         elem.addNamespaceDeclaration(att.getName().substring(XMLConstants.XMLNS_ATTRIBUTE.length() + 1), att.getValue());
93                         elem.setAttributeNS(att.getNamespaceURI(), att.getName(), att.getValue());
94                     }
95                 }
96             }
97             // The following code works with axis saaj implementation
98
for (Iterator JavaDoc itNs = parent.getNamespacePrefixes(); itNs.hasNext();) {
99                 String JavaDoc prefix = (String JavaDoc) itNs.next();
100                 String JavaDoc nsuri = parent.getNamespaceURI(prefix);
101                 if (elem.getAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix) == null) {
102                     elem.addNamespaceDeclaration(prefix, nsuri);
103                     elem.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLConstants.XMLNS_ATTRIBUTE + ":" + prefix, nsuri);
104                 }
105             }
106         }
107         
108         if (log.isDebugEnabled()) {
109             try {
110                 log.debug(transformer.toString(elem));
111             } catch (Exception JavaDoc e) { }
112         }
113         
114         normalizedMessage.setContent(new DOMSource JavaDoc(elem));
115
116         addNmsAttachments(normalizedMessage, soapMessage);
117     }
118
119     public SOAPMessage JavaDoc createSOAPMessage(NormalizedMessage normalizedMessage) throws SOAPException JavaDoc, IOException JavaDoc, TransformerException JavaDoc, MessagingException, ParserConfigurationException JavaDoc, SAXException JavaDoc {
120         SOAPMessage JavaDoc soapMessage = getMessageFactory().createMessage();
121
122         addSoapProperties(soapMessage, normalizedMessage);
123
124         SOAPPart JavaDoc soapPart = soapMessage.getSOAPPart();
125         SOAPEnvelope JavaDoc envelope = soapPart.getEnvelope();
126         SOAPBody JavaDoc body = envelope.getBody();
127
128         // lets turn the payload into a DOM Node to avoid blatting over the envelope
129
// Do not use DOMResult to transform as namespaces are lost (why ?)
130
//DOMResult result = new DOMResult(null);
131
//transformer.toResult(normalizedMessage.getContent(), result);
132
//Document document = (Document) result.getNode();
133
Document JavaDoc document = transformer.toDOMDocument(normalizedMessage);
134         body.addDocument(document);
135
136         addSoapAttachments(soapMessage, normalizedMessage);
137
138         return soapMessage;
139     }
140
141     // Properties
142
//-------------------------------------------------------------------------
143
public MessageFactory JavaDoc getMessageFactory() throws SOAPException JavaDoc {
144         if (messageFactory == null) {
145             messageFactory = createMessageFactory();
146         }
147         return messageFactory;
148     }
149
150     public void setMessageFactory(MessageFactory JavaDoc messageFactory) {
151         this.messageFactory = messageFactory;
152     }
153
154     // Implementation methods
155
//-------------------------------------------------------------------------
156

157     protected void addNmsProperties(NormalizedMessage normalizedMessage, SOAPMessage JavaDoc soapMessage) {
158         Iterator JavaDoc iter = soapMessage.getMimeHeaders().getAllHeaders();
159         while (iter.hasNext()) {
160             MimeHeader JavaDoc header = (MimeHeader JavaDoc) iter.next();
161             normalizedMessage.setProperty(header.getName(), header.getValue());
162         }
163     }
164
165     protected void addNmsAttachments(NormalizedMessage normalizedMessage, SOAPMessage JavaDoc soapMessage) throws MessagingException, SOAPException JavaDoc {
166         Iterator JavaDoc iter = soapMessage.getAttachments();
167         while (iter.hasNext()) {
168             AttachmentPart JavaDoc attachment = (AttachmentPart JavaDoc) iter.next();
169             normalizedMessage.addAttachment(attachment.getContentId(), asDataHandler(attachment));
170         }
171     }
172
173     protected void addSoapProperties(SOAPMessage JavaDoc soapMessage, NormalizedMessage normalizedMessage) throws SOAPException JavaDoc {
174         for (Iterator JavaDoc iter = normalizedMessage.getPropertyNames().iterator(); iter.hasNext();) {
175             String JavaDoc name = (String JavaDoc) iter.next();
176             Object JavaDoc value = normalizedMessage.getProperty(name);
177             if (shouldIncludeHeader(normalizedMessage, name, value)) {
178                 soapMessage.getMimeHeaders().addHeader(name, value.toString());
179             }
180             if (shouldIncludeProperty(normalizedMessage, name, value)) {
181                 soapMessage.setProperty(name, value);
182             }
183         }
184     }
185
186     protected void addSoapAttachments(SOAPMessage JavaDoc soapMessage, NormalizedMessage normalizedMessage) throws IOException JavaDoc {
187         Iterator JavaDoc iterator = normalizedMessage.getAttachmentNames().iterator();
188         while (iterator.hasNext()) {
189             String JavaDoc name = (String JavaDoc) iterator.next();
190             DataHandler JavaDoc attachment = normalizedMessage.getAttachment(name);
191             AttachmentPart JavaDoc attachmentPart = soapMessage.createAttachmentPart(attachment.getContent(), attachment.getContentType());
192             attachmentPart.setContentId(name);
193             soapMessage.addAttachmentPart(attachmentPart);
194         }
195     }
196
197     /**
198      * Decides whether or not the given header should be included in the SAAJ message as a MimeHeader
199      */

200     protected boolean shouldIncludeHeader(NormalizedMessage normalizedMessage, String JavaDoc name, Object JavaDoc value) {
201         // TODO: remove http headers that may come from a consumer http BC
202
return true;
203     }
204
205     /**
206      * Decides whether or not the given property should be included in the SAAJ message as a property
207      */

208     protected boolean shouldIncludeProperty(NormalizedMessage normalizedMessage, String JavaDoc name, Object JavaDoc value) {
209         return true;
210     }
211
212     protected DataHandler JavaDoc asDataHandler(AttachmentPart JavaDoc attachment) throws SOAPException JavaDoc {
213         return new DataHandler JavaDoc(attachment.getContent(), attachment.getContentType());
214     }
215
216
217     protected MessageFactory JavaDoc createMessageFactory() throws SOAPException JavaDoc {
218         return MessageFactory.newInstance();
219     }
220 }
221
Popular Tags