File: SOAPMessageImpl.java

package info (click to toggle)
libjboss-web-services-java 0.0%2Bsvn5660%2Bdak2-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 7,276 kB
  • sloc: java: 79,207; xml: 29; makefile: 19; sh: 16
file content (532 lines) | stat: -rw-r--r-- 15,941 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.ws.core.soap;

// $Id: SOAPMessageImpl.java 5034 2007-11-12 14:08:23Z alessio.soldano@jboss.com $

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.mail.MessagingException;
import javax.xml.soap.AttachmentPart;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;

import org.jboss.ws.Constants;
import org.jboss.ws.WSException;
import org.jboss.ws.core.CommonMessageContext;
import org.jboss.ws.core.SOAPMessageAbstraction;
import org.jboss.ws.core.soap.attachment.AttachmentPartImpl;
import org.jboss.ws.core.soap.attachment.CIDGenerator;
import org.jboss.ws.core.soap.attachment.MimeConstants;
import org.jboss.ws.core.soap.attachment.MultipartRelatedEncoder;
import org.jboss.ws.core.soap.attachment.MultipartRelatedSwAEncoder;
import org.jboss.ws.core.soap.attachment.MultipartRelatedXOPEncoder;
import org.jboss.ws.extensions.xop.XOPContext;
import org.jboss.ws.metadata.umdm.EndpointMetaData;
import org.jboss.ws.metadata.umdm.OperationMetaData;

/**
 * The root class for all SOAP messages. As transmitted on the "wire", a SOAP message is an XML document or a
 * MIME message whose first body part is an XML/SOAP document.
 *
 * @author Thomas.Diesler@jboss.org
 * @author <a href="mailto:jason@stacksmash.com">Jason T. Greene</a>
 */
public class SOAPMessageImpl extends SOAPMessage implements SOAPMessageAbstraction
{
   private boolean saveRequired = true;
   private MimeHeaders mimeHeaders = new MimeHeaders();
   private List<AttachmentPart> attachments = new LinkedList<AttachmentPart>();
   private CIDGenerator cidGenerator = new CIDGenerator();
   private boolean isXOPMessage;
   private boolean isSWARefMessage;
   private SOAPPartImpl soapPart;   
   private MultipartRelatedEncoder multipartRelatedEncoder;

   // Cache the associated operation meta data
   private OperationMetaData opMetaData;

   SOAPMessageImpl() throws SOAPException
   {
      soapPart = new SOAPPartImpl(this);
      setProperty(CHARACTER_SET_ENCODING, "UTF-8");
      setProperty(WRITE_XML_DECLARATION, false);
   }

   public CIDGenerator getCidGenerator()
   {
      return cidGenerator;
   }

   public boolean isXOPMessage()
   {
      return isXOPMessage;
   }

   public void setXOPMessage(boolean isXOPMessage)
   {
      this.isXOPMessage = isXOPMessage;
   }

   public boolean isSWARefMessage()
   {
      return isSWARefMessage;
   }

   public void setSWARefMessage(boolean isSWAMessage)
   {
      this.isSWARefMessage = isSWAMessage;
   }

   public void setAttachments(Collection<AttachmentPart> parts) throws SOAPException
   {
      for (AttachmentPart part : parts)
      {
         attachments.add(part);
      }
      saveRequired = true;
   }

   public void addAttachmentPart(AttachmentPart part)
   {
      if (part == null)
         return;

      attachments.add(part);
      saveRequired = true;
   }

   public AttachmentPart getAttachmentByContentId(String cid) throws SOAPException
   {
      for (AttachmentPart part : attachments)
      {
         String contentId = part.getContentId();
         if (contentId.equals(cid))
            return part;
      }
      return null;
   }

   public AttachmentPart removeAttachmentByContentId(String cid)
   {
      for (AttachmentPart part : attachments)
      {
         String contentId = part.getContentId();
         if (contentId.equals(cid))
         {
            attachments.remove(part);
            return part;
         }
      }

      return null;
   }

   public AttachmentPart getAttachmentByPartName(String partName)
   {
      for (AttachmentPart part : attachments)
      {
         String contentId = part.getContentId();
         if (contentId.startsWith("<" + partName + "="))
            return part;
      }
      return null;
   }

   public AttachmentPart createAttachmentPart()
   {
      return new AttachmentPartImpl();
   }

   public String getContentDescription()
   {
      String[] value = mimeHeaders.getHeader(MimeConstants.CONTENT_DESCRIPTION);

      return (value == null) ? null : value[0];
   }

   public void setContentDescription(String description)
   {
      mimeHeaders.setHeader(MimeConstants.CONTENT_DESCRIPTION, description);
   }

   public MimeHeaders getMimeHeaders()
   {
      return mimeHeaders;
   }

   public void setMimeHeaders(MimeHeaders headers)
   {
      if (headers == null)
         throw new IllegalArgumentException("MimeHeaders cannot be null");
      this.mimeHeaders = headers;
   }

   public SOAPPart getSOAPPart()
   {
      return soapPart;
   }

   public void removeAllAttachments()
   {
      attachments.clear();
      saveRequired = true;
   }

   public int countAttachments()
   {
      return attachments.size();
   }

   public Iterator getAttachments()
   {
      // Someone could call remove on this iterator, affecting the attachment count
      saveRequired = true;
      return attachments.iterator();
   }

   public Iterator getAttachments(MimeHeaders headers)
   {
      if (headers == null)
         throw new WSException("MimeHeaders can not be null");

      return new MimeMatchingAttachmentsIterator(headers, attachments);
   }
   
   private String getSOAPContentType() throws SOAPException
   {
      //Check binding type in the endpoint metadata
      CommonMessageContext msgContext = MessageContextAssociation.peekMessageContext();
      if (msgContext != null && Constants.SOAP12HTTP_BINDING.equalsIgnoreCase(msgContext.getEndpointMetaData().getBindingId()))
      {
         return SOAPConstants.SOAP_1_2_CONTENT_TYPE;
      }
      //Check the message envelope
      SOAPEnvelope env = soapPart != null ? soapPart.getEnvelope() : null;
      if (env != null && SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE.equals(env.getNamespaceURI()))
      {
         return SOAPConstants.SOAP_1_2_CONTENT_TYPE;
      }
      //Default to soap 1.1
      return SOAPConstants.SOAP_1_1_CONTENT_TYPE;
   }
   
   public void saveChanges() throws SOAPException
   {
      if (saveRequired == true)
      {
         try
         {
            boolean hasAttachments = attachments.size() > 0;

            if (isXOPMessage() && !XOPContext.isMTOMEnabled() && hasAttachments)
               throw new IllegalStateException("XOP parameter not properly inlined");

            // default content-type
            String contentType = getSOAPContentType() + "; charset=" + getCharSetEncoding();

            if (hasAttachments)
            {
               if (isXOPMessage() && XOPContext.isMTOMEnabled())
               {
                  multipartRelatedEncoder = new MultipartRelatedXOPEncoder(this);
                  multipartRelatedEncoder.encodeMultipartRelatedMessage();
                  contentType = multipartRelatedEncoder.getContentType();
               }
               else
               {
                  multipartRelatedEncoder = new MultipartRelatedSwAEncoder(this);
                  multipartRelatedEncoder.encodeMultipartRelatedMessage();
                  contentType = multipartRelatedEncoder.getContentType();
               }
            }

            mimeHeaders.setHeader(MimeConstants.CONTENT_TYPE, contentType);
         }
         catch (MessagingException ex)
         {
            throw new SOAPException(ex);
         }

         /*
          * We are lazily encoding our message, which means that currently
          * Content-Length is not being calculated. This should not be a problem
          * because HTTP/1.1 does not require that it be sent (WS Basic Profile 1.1
          * states that implementations SHOULD send HTTP 1.1). If it is determined
          * that it must be sent, this perhaps should be done by the transport
          * layer. However, there could be a space optimization where length is
          * precalulated per attachment, and that calculation would, of course,
          * belong here.
          */

         saveRequired = false;
      }

      CommonMessageContext msgContext = MessageContextAssociation.peekMessageContext();
      if(msgContext!=null) msgContext.setModified(true);
   }

   public boolean saveRequired()
   {
      return saveRequired;
   }

   public void writeTo(OutputStream outs) throws IOException
   {
      try
      {
         // Save all changes
         saveChanges();

         // If there are attachments then we delegate encoding to MultipartRelatedEncoder
         if (attachments.size() > 0)
         {
            multipartRelatedEncoder.writeTo(outs);
         }
         else
         {
            SOAPEnvelope soapEnv = getSOAPPart().getEnvelope();
            if (soapEnv != null)
            {
               boolean writeXML = isWriteXMLDeclaration();
               String charsetEncoding = getCharSetEncoding();
               SOAPElementWriter writer = new SOAPElementWriter(outs, charsetEncoding);
               writer.setWriteXMLDeclaration(writeXML).writeElement((SOAPEnvelopeImpl)soapEnv);
            }
         }
      }
      catch (SOAPException ex)
      {
         WSException.rethrow(ex);
      }
   }

   private String getCharSetEncoding() throws SOAPException
   {
      String charsetName = (String)getProperty(CHARACTER_SET_ENCODING);
      if (charsetName == null)
         charsetName = "UTF-8";
      return charsetName;
   }

   /** Get the operation meta data for this SOAP message
    */
   public OperationMetaData getOperationMetaData(EndpointMetaData epMetaData) throws SOAPException
   {
      if (opMetaData == null)
      {
         SOAPMessageDispatcher dispatcher = new SOAPMessageDispatcher();
         opMetaData = dispatcher.getDispatchDestination(epMetaData, this);
      }
      return opMetaData;
   }

   public boolean isFaultMessage()
   {
      SOAPFault soapFault = null;
      try
      {
         soapFault = getSOAPBody().getFault();
      }
      catch (Exception ignore)
      {
      }
      return soapFault != null;
   }

   private boolean isWriteXMLDeclaration() throws SOAPException
   {
      Boolean booleanValue = new Boolean(false);
      Object propValue = getProperty(WRITE_XML_DECLARATION);
      if (propValue instanceof Boolean)
         booleanValue = (Boolean)propValue;
      if (propValue instanceof String)
         booleanValue = new Boolean((String)propValue);
      return booleanValue.booleanValue();
   }

   public static class MimeMatchingAttachmentsIterator implements Iterator
   {
      private Iterator iterator;

      private MimeHeaders headers = new MimeHeaders();

      private AttachmentPart lastMatch;

      public MimeMatchingAttachmentsIterator(MimeHeaders headers, List attachments)
      {
         iterator = attachments.iterator();

         if (headers != null)
            this.headers = headers;
      }

      private boolean containsAllHeaders(Iterator headerIterator, AttachmentPart part)
      {
         while (headerIterator.hasNext())
         {
            MimeHeader header = (MimeHeader)headerIterator.next();
            String[] values = part.getMimeHeader(header.getName());
            if (values == null)
               return false;

            boolean match = false;
            for (int j = 0; j < values.length; j++)
            {
               if (values[j].equalsIgnoreCase(header.getValue()))
               {
                  match = true;
                  break;
               }
            }

            if (!match)
               return false;
         }

         return true;
      }

      private void nextMatch()
      {
         while (iterator.hasNext())
         {
            AttachmentPart part = (AttachmentPart)iterator.next();
            if (containsAllHeaders(headers.getAllHeaders(), part))
            {
               lastMatch = part;
               break;
            }
         }
      }

      public boolean hasNext()
      {
         if (lastMatch == null)
            nextMatch();

         return lastMatch != null;
      }

      public Object next()
      {
         if (!hasNext())
            return null;

         Object retval = lastMatch;
         lastMatch = null;

         return retval;
      }

      public void remove()
      {
         iterator.remove();
      }
   }

   @Override
   public AttachmentPart getAttachment(SOAPElement element) throws SOAPException
   {
      String ref = element.getAttribute("href");

      if (ref.length() == 0)
      {
         ref = element.getValue();
         if (ref == null || ref.length() == 0)
            return null;
      }

      return getAttachmentByRef(ref);
   }

   private AttachmentPart getAttachmentByRef(String ref) throws SOAPException
   {
      AttachmentPart attachment;
      if (ref.startsWith("cid:"))
      {
         /* SwA 2000-12-11 section 3: if a Content-ID header is present, then an absolute URI 
          * label for the part is formed using the CID URI scheme
          * 
          * WS-I AP 1.0 section 3.5: when using the CID URI scheme, the syntax and rules defined
          * in RFC 2392 apply.
          */
         String cid = '<' + ref.substring("cid:".length()) + '>';
         attachment = getAttachmentByContentId(cid);
      }
      else
      {
         /* SwA 2000-12-11 section 3: If a Content-Location header is present with an absolute URI
          * value then that URI is a label for the part
          */
         attachment = getAttachmentByContentLocation(ref);
      }

      if (attachment == null)
      {
         // autogenerated CID based on part name
         attachment = getAttachmentByPartName(ref);
      }

      return attachment;
   }

   /**
    * Looks for the first {@linkplain AttachmentPart attachment} where the
    * {@linkplain AttachmentPart#getContentLocation() content location} matches the
    * given <code>location</code>.
    * @param location the content location to match
    * @return the matching attachment or <code>null</code> if no match was found
    */
   private AttachmentPart getAttachmentByContentLocation(String location)
   {
      for (AttachmentPart attachment : attachments)
      {
         if (location.equals(attachment.getContentLocation()))
            return attachment;
      }
      return null;
   }

   @Override
   public void removeAttachments(MimeHeaders headers)
   {
      /* this code exploits the fact that MimeMatchingAttachmentsIterator.next() returns null
       * rather than throwing an exception when there are no more elements 
       */
      Iterator attachmentItr = new MimeMatchingAttachmentsIterator(headers, attachments);
      while (attachmentItr.next() != null)
         attachmentItr.remove();
   }
}